show me the code
#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>
#include<string.h>
#include<sys/stat.h>
#include<sys/types.h>
#include<fcntl.h>
#include<sys/wait.h>
#include<sys/mman.h>
#include<pthread.h>
#include<semaphore.h>
sem_t empty;
sem_t full;
int number=0;
pthread_mutex_t mutex;
typedef struct node{
int date;
struct node *next;
}Node;
Node *head=NULL;
void* producer(void *arg){
while(1){
sem_wait(&empty);
pthread_mutex_lock(&mutex);
Node *p=(Node *)malloc(sizeof(Node));
p->date=rand()%100;
p->next=head;
head=p;
number++;
printf("produce id = %lu, 当前产品有%d个\t, %d\n", pthread_self(), number, p->date);
pthread_mutex_unlock(&mutex);
sem_post(&full);
}
return NULL;
}
void* consumer(void *arg){
while(1){
sem_wait(&full);
pthread_mutex_lock(&mutex);
Node*pp=head;
head=head->next;
printf("CONSUMER id = %lu, 当前产品有%d个\t, %d\n", pthread_self(), number, pp->date);
free(pp);
if(pp!=NULL)pp=NULL;
number--;
pthread_mutex_unlock(&mutex);
sem_post(&empty);
}
return NULL;
}
int main(int argc,char *argv[]){
pthread_t pthid[2];
pthread_mutex_init(&mutex,NULL);
sem_init(&empty,0,3);
sem_init(&full,0,0);
pthread_create(&pthid[0],NULL,producer,NULL);
pthread_create(&pthid[1],NULL,consumer,NULL);
// pthread_join(pthid[0],NULL);
// pthread_join(pthid[1],NULL);
pthread_detach(pthid[0]);
pthread_detach(pthid[1]);
sleep(3);
sem_destroy(&empty);
sem_destroy(&full);
pthread_mutex_destroy(&mutex);
exit(0);
}