Created
October 24, 2019 15:08
-
-
Save byyam/874a165961b2084610f6c3b14b903f4c to your computer and use it in GitHub Desktop.
pthread_producer_consumer
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 <unistd.h> | |
#include <pthread.h> | |
#include <stdio.h> | |
struct msg { | |
struct msg *next; | |
int num; | |
}; | |
struct msg *head; | |
pthread_cond_t has_product = PTHREAD_COND_INITIALIZER; | |
pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER; | |
void *consumer(void *p) | |
{ | |
struct msg *mp; | |
for (;;) { | |
pthread_mutex_lock(&lock);//get the lock | |
while(head == NULL) | |
pthread_cond_wait(&has_product, &lock);//1. release lock. 2. waiting for the event. 3. get the lock, continue. | |
mp = head; | |
head = mp->next; | |
pthread_mutex_unlock(&lock);//release the lock | |
printf("Consume %d\n", mp->num); | |
free(mp); | |
sleep(rand() % 5); | |
} | |
} | |
void *producer(void *p) | |
{ | |
struct msg *mp; | |
for (;;) { | |
mp = (struct msg *)malloc(sizeof(struct msg)); | |
mp->num = rand() % 1000 + 1; | |
printf("Produce %d\n", mp->num); | |
pthread_mutex_lock(&lock);//get the lock | |
mp->next = head; | |
head = mp; | |
pthread_mutex_unlock(&lock);//release the lock | |
pthread_cond_signal(&has_product);//send signal to notice event | |
sleep(rand() % 5); | |
} | |
} | |
int main(int argc, char *argv[]) | |
{ | |
pthread_t pid, cid; | |
srand(time(NULL)); | |
pthread_create(&pid, NULL, producer, NULL); | |
pthread_create(&cid, NULL, consumer, NULL); | |
pthread_join(pid, NULL);//waiting for pthread termination | |
pthread_join(cid, NULL); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment