多线程编程之:实验内容——“生产者消费者”实验
rd_cst_id;
pthread_t mon_th_id;
int ret;
srand(time(NULL));
end_time = time(NULL) + RUN_TIME;
/*创建有名管道*/
if((mkfifo(MYFIFO, O_CREAT|O_EXCL) < 0) && (errno != EEXIST))
{
printf("Cannot create fifo\n");
return errno;
}
/*打开管道*/
fd = open(MYFIFO, O_RDWR);
if (fd == -1)
{
printf("Open fifo error\n");
return fd;
}
/*初始化互斥信号量为1*/
ret = sem_init(&mutex, 0, 1);
/*初始化avail信号量为N*/
ret += sem_init(&avail, 0, BUFFER_SIZE);
/*初始化full信号量为0*/
ret += sem_init(&full, 0, 0);
if (ret != 0)
{
printf("Any semaphore initialization failed\n");
return ret;
}
/*创建两个线程*/
ret = pthread_create(&thrd_prd_id, NULL, producer, NULL);
if (ret != 0)
{
printf("Create producer thread error\n");
return ret;
}
ret = pthread_create(&thrd_cst_id, NULL, customer, NULL);
if(ret != 0)
{
printf("Create customer thread error\n");
return ret;
}
pthread_join(thrd_prd_id, NULL);
pthread_join(thrd_cst_id, NULL);
close(fd);
unlink(MYFIFO);
return 0;
}
4.实验结果
运行该程序,得到如下结果:
$ ./producer_customer
……
Producer: delay = 3
Write 5 to the FIFO
Customer: delay = 3
Read hello from FIFO
Producer: delay = 1
Write 5 to the FIFO
Producer: delay = 2
Write 5 to the FIFO
Customer: delay = 4
Read hello from FIFO
Customer: delay = 1
Read hello from FIFO
Producer: delay = 2
Write 5 to the FIFO
……
- linux多线程编程技术(05-29)
- 《嵌入式Linux应用程序开发标准教程》(第2版)(09-30)
- 现代通信系统与DSP实验平台(07-12)
- AT89S51单片机实验系统的开发与应用(06-21)
- 基于VRML和JavaScript的数码摄影虚拟实验系统的设计与实现(09-20)
- 通信系统原理技术与DSP实验平台的研制(06-06)