- UID
- 1029342
- 性别
- 男
|
#include <stdio.h>
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <pthread.h>
#include <semaphore.h>
//[1].两类资源
//读资源
sem_t sem_r;
//写资源
sem_t sem_w;
//全局缓冲区
char buf[1024] = {0};
//读线程
void* thread_r(void *arg)
{
while(1)
{
//申请读资源
sem_wait(&sem_r);
//读操作
printf("buf: %s\n",buf);
//此时buf被读,可写
sem_post(&sem_w);
}
}
//写线程
void * thread_w(void *arg)
{
while(1)
{
//申请写资源
sem_wait(&sem_w);
//写操作--必须先获得写资源
putchar('>');
fgets(buf,sizeof(buf),stdin); //写入数据
//buf中被写入了数据,此时成为读资源
sem_post(&sem_r);
}
}
int main(int argc, const char *argv[])
{
pthread_t tid[2];
int ret = 0;
//(1).初始化
sem_init(&sem_r,0,0);
sem_init(&sem_w,0,1);
ret = pthread_create(&tid[0],NULL,thread_r,NULL);
if(ret != 0)
{
errno = ret;
perror("pthread_create fail");
exit(EXIT_FAILURE);
}
ret = pthread_create(&tid[1],NULL,thread_w,NULL);
if(ret != 0)
{
errno = ret;
perror("pthread_create fail");
exit(EXIT_FAILURE);
}
printf("main thread run ......\n");
int i = 0;
for(; i < 2; i++)
{
pthread_join(tid[i],NULL);
}
return 0;
} |
|