Last active
May 14, 2019 02:45
-
-
Save mrMustacho/dc8b37c5ae30ca86532360a4463a4bd3 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdlib.h> | |
#include <stdio.h> | |
#include <pthread.h> | |
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; | |
typedef struct node{ | |
int data; | |
struct node* next; | |
} node; | |
typedef struct __myarg_t { | |
int data; | |
struct node* head; | |
} myarg_t; | |
void print_list(node* head) | |
{ | |
node* cursor = head; | |
while(cursor != NULL) | |
{ | |
printf("%d ", cursor->data); | |
cursor = cursor->next; | |
} | |
} | |
node* create(int data,node* next) | |
{ | |
node* new_node = (node*)malloc(sizeof(node)); | |
if(new_node == NULL) | |
{ | |
printf("Error creating a new node.\n"); | |
exit(0); | |
} | |
new_node->data = data; | |
new_node->next = next; | |
return new_node; | |
} | |
node* append(node* head, int data) | |
{ | |
/* go to the last node */ | |
node *cursor = head; | |
while(cursor->next != NULL) | |
cursor = cursor->next; | |
/* create a new node */ | |
node* new_node = create(data,NULL); | |
cursor->next = new_node; | |
return head; | |
} | |
node* remove_front(node* head) | |
{ | |
if(head == NULL) | |
return NULL; | |
node *front = head; | |
head = head->next; | |
front->next = NULL; | |
/* is this the last node in the list */ | |
if(front == head) | |
head = NULL; | |
free(front); | |
return head; | |
} | |
node* remove_back(node* head) | |
{ | |
if(head == NULL) | |
return NULL; | |
node *cursor = head; | |
node *back = NULL; | |
while(cursor->next != NULL) | |
{ | |
back = cursor; | |
cursor = cursor->next; | |
} | |
if(back != NULL) | |
back->next = NULL; | |
/* if this is the last node in the list*/ | |
if(cursor == head) | |
head = NULL; | |
free(cursor); | |
return head; | |
} | |
void *mythread(void *arg) | |
{ | |
myarg_t *m = (myarg_t *) arg; | |
while(m->data < 101){ | |
pthread_mutex_lock(&mutex); | |
m->head = append(m->head, m->data); | |
m->data += 1; | |
pthread_mutex_unlock(&mutex); | |
} | |
return NULL; | |
} | |
int main(void) | |
{ | |
node* head = NULL; | |
// inserte código para agregar 100 nodos | |
// primero secuencialmente (usando un ciclo) | |
// luego en paralelo | |
head = create(0, NULL); | |
if(head == NULL) | |
{ | |
printf("Error creating a new node.\n"); | |
exit(0); | |
} | |
pthread_t p1; | |
pthread_t p2; | |
myarg_t args; | |
args.head = head; | |
args.data = 1; | |
pthread_create(&p1, NULL, mythread, &args); | |
pthread_create(&p2, NULL, mythread, &args); | |
pthread_join(p1, NULL); | |
pthread_join(p2, NULL); | |
print_list(head); | |
printf("\nListo!\n"); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment