微波EDA网,见证研发工程师的成长!
首页 > 硬件设计 > 嵌入式设计 > 多线程编程之:实验内容——“生产者消费者”实验

多线程编程之:实验内容——“生产者消费者”实验

时间:08-13 来源:3721RD 点击:

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

……

Copyright © 2017-2020 微波EDA网 版权所有

网站地图

Top