生产者消费者
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>
#include <sys/types.h>
#include <string.h>
struct Node{
int val;
Node* next;
};
pthread_mutex_t mutex;
pthread_cond_t cond;
Node* head = NULL;
void* producter(void* argv){
while(1){
Node* p = (Node*)malloc(sizeof(Node));
p->val = rand() % 1000;
pthread_mutex_lock(&mutex);
printf("sheng chan le %d\n", p->val);
p->next = head;
head = p;
pthread_mutex_unlock(&mutex);
sleep(1);
pthread_cond_signal(&cond);
}
}
void* customer(void* argv){
Node* p = NULL;
while(1){
pthread_mutex_lock(&mutex);
if (head == NULL) {
pthread_cond_wait(&cond, &mutex);
}
if (head == NULL) {
pthread_mutex_unlock(&mutex);
continue;
}
printf("xiao fei le %d\n", head->val);
p = head;
head = head->next;
pthread_mutex_unlock(&mutex);
free(p);
p = NULL;
}
}
int main()
{
pthread_mutex_init(&mutex, NULL);
pthread_cond_init(&cond, NULL);
pthread_t thread1;
pthread_create(&thread1, NULL, customer, NULL);
pthread_t thread2;
pthread_create(&thread2, NULL, producter, NULL);
pthread_join(thread1, NULL);
pthread_join(thread2, NULL);
pthread_mutex_destroy(&mutex);
pthread_cond_destroy(&cond);
return 0;
}