Skip to content

Instantly share code, notes, and snippets.

@Jorvan758
Created May 1, 2019 01:11
Show Gist options
  • Save Jorvan758/9354ede265b98ce452af530dfa2edc28 to your computer and use it in GitHub Desktop.
Save Jorvan758/9354ede265b98ce452af530dfa2edc28 to your computer and use it in GitHub Desktop.
Tarea con y sin paralelismo
#include <stdlib.h>
#include <stdio.h>
#include <pthread.h>
#include <semaphore.h>
typedef struct node{
int data;
struct node* next;
} node;
void print_list(node* head)
{
node* cursor = head;
while(cursor != NULL)
{
printf("%d \n", 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;
}
sem_t mutex;
void *unosnodos(void *head2){ //Creado por mí
for(int contadore = 0; contadore < 50; contadore++){
sem_wait(&mutex);
head2 = append(head2, contadore+1);
sem_post(&mutex);
}
return NULL;
}
int main(void) {
node* head = NULL;
// inserte código para agregar 100 nodos
// primero secuencialmente (usando un ciclo)
int contador = 0;
head = create(0, NULL);
for(contador = 0; contador < 100; contador++){
head = append(head, contador+1);
}
print_list(head);
printf("\n");
// luego en paralelo
node* head2 = create(0, NULL);
sem_init(&mutex, 0, 1);
pthread_t thread_id1;
pthread_t thread_id2;
pthread_create(&thread_id1, NULL, unosnodos, head2);
pthread_create(&thread_id2, NULL, unosnodos, head2);
pthread_join(thread_id1, NULL);
pthread_join(thread_id2, NULL);
print_list(head2);
printf("\nListo!\n");
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment