//mutex.c
#include <stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include <pthread.h>
#include <string.h>
void* reader_function(void *p);
void* writer_function(void *p);
char buffer[10]={0};
int buffer_has_item=0;
pthread_mutex_t mutex;
int main(void)
{
pthread_t reader;
pthread_mutex_init(&mutex,NULL);
pthread_create(&reader,NULL, reader_function, NULL);
writer_function(NULL);
}
void* writer_function(void *p)
{
int i,ti;
for(i=1;i<3;)
{
ti=i;
/* .....*/
pthread_mutex_lock(&mutex);
printf("Writer %d Locked Buffer.\r\n",i);
if (buffer_has_item==0)
{
buffer_has_item=1;
strcpy(buffer,"Full");
printf("++Writer %d fill the buffer with context \"%s\".\r\n",i,buffer);
i++;
}
/* .....*/
printf("Writer %d Unlocked Buffer.\r\n\n\n",ti);
pthread_mutex_unlock(&mutex);
sleep(1);
}
return NULL;
}
void* reader_function(void *p)
{
int i,ti;
for(i=1;i<3;)
{
ti=i;
pthread_mutex_lock(&mutex);
printf("Reader %d Locked Buffer.\r\n",i);
if(buffer_has_item==1)
{
buffer_has_item=0;
strcpy(buffer,"Empty");
printf("--Reader %d clean the buffer with context \"%s\".\r\n",i,buffer);
i++;
}
printf("Reader %d Unlocked Buffer.\r\n\n\n",ti);
pthread_mutex_unlock(&mutex);
sleep(1);
}
return NULL;
}
编译命令:gcc -o mutex -lpthread -g mutex.c
执行./mutex
浙公网安备 33010602011771号