小樱知识 > 生活常识多线程编程(c++多线程编程)

多线程编程(c++多线程编程)

提问时间:2022-05-29 11:08:12来源:小樱知识网


上面的示例可能很乏味,但下面的代码示例更简洁:

#include#include#include#include#include#include#include#define NUM 3pthread_cond_t condv = PTHREAD_COND_INITIALIZER;pthread_mutex_t mlock = PTHREAD_MUTEX_INITIALIZER; void producer(void* arg) {    int n = NUM;    while(n--) {        sleep(1);        pthread_cond_signal(&condv);        printf(\"producer thread send notify signal. %d\\t\", NUM-n);    }}void consumer(void* arg) {    int n = 0;    while (1) {        pthread_cond_wait(&condv, &mlock);        printf(\"recv producer thread notify signal. %d\\n\", ++n);        if (NUM == n) {            break;        }    }}int main() {    pthread_t tid1, tid2;    pthread_create(&tid1, NULL, (void*)producer, NULL);    pthread_create(&tid2, NULL, (void*)consumer, NULL);        pthread_join(tid1, NULL);    pthread_join(tid2, NULL);    return 0;}

运行结果:

producer thread send notify signal. 1   recv producer thread notify signal. 1producer thread send notify signal. 2   recv producer thread notify signal. 2producer thread send notify signal. 3   recv producer thread notify signal. 3

[3]旗语

信号量适用于控制只支持有限数量用户的共享资源。用于将计数值保持在0和指定的最大值之间。当线程完成一次对信号量对象的等待时,计数值减一;当线程完成释放信号量对象一次时,计数值增加1。当计数值为0时,线程挂起并等待,直到计数值超过0。

主要功能如下:

#include int sem_init(sem_t *sem, int pshared, unsigned int value);int sem_wait(sem_t *sem);int sem_trywait(sem_t *sem);int sem_post(sem_t * sem);int sem_destroy(sem_t * sem);

代码示例如下:

#include#include#include#include#include#include#include#include#define NUM 5int queue[NUM];sem_t psem, csem; void producer(void* arg) {    int pos = 0;    int num, count = 0;    for (int i=0; i

以上内容就是为大家推荐的多线程编程(c++多线程编程)最佳回答,如果还想搜索其他问题,请收藏本网站或点击搜索更多问题

内容来源于网络仅供参考
二维码

扫一扫关注我们

版权声明:所有来源标注为小樱知识网www.xiaoyin02.com的内容版权均为本站所有,若您需要引用、转载,只需要注明来源及原文链接即可。

本文标题:多线程编程(c++多线程编程)

本文地址:https://www.xiaoyin02.com/shcs/241846.html

相关文章