#include <cstdio>
#include<pthread.h>
#include <iostream>
#include<unistd.h>
#include<string.h>
using namespace std;
typedef struct node {
int data;
struct node* next;
}Node;
Node *head = NULL;
pthread_mutex_t mutex;
pthread_cond_t cond;
void* producer(void *arg) {
while (1) {
Node* p = new Node;
p->data = rand() % 1000;
pthread_mutex_lock(&mutex);
p->next = head;
head = p;
cout << "====produce:" << pthread_self() << " " << p->data << endl;
pthread_mutex_unlock(&mutex);
pthread_cond_signal(&cond);
sleep(rand() % 3);
}
return NULL;
}
void* customer(void *arg) {
while (1) {
pthread_mutex_lock(&mutex);
if (head == NULL) {
pthread_cond_wait(&cond, &mutex);
}
Node* pdel = head;
head = head->next;
cout << "--------customer: " << pthread_self() << " " << pdel->data << endl;
delete pdel;
pthread_mutex_unlock(&mutex);
}
return NULL;
}
int main()
{
pthread_t p1, p2;
pthread_mutex_init(&mutex, NULL);
pthread_cond_init(&cond, NULL);
pthread_create(&p1, NULL, producer, NULL);
pthread_create(&p2, NULL, customer, NULL);
pthread_join(p1, NULL);
pthread_join(p2, NULL);
return 0;
}