国学经典,永久流传《诗经朗诵全集》
《诗经朗诵全集》带你领略国学经典,永久咏传。...
2023-07-31
上面的示例可能很乏味,但下面的代码示例更简洁:
#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
信号量适用于控制只支持有限数量用户的共享资源。用于将计数值保持在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
相关文章
热点文章
2021年独生子女补贴新政策是真的吗(独生子女证有有效期吗)
2021年国庆节阅兵仪式几点开始几点结束(2021年国庆节还有阅兵吗)
鼠目寸光一点红是什么生肖动物(鼠目寸光一点红)指什么生肖,紧密
k0到k9的玩法大全(强制gc的玩法和注意事项)
入土为安是什么生肖《入土为安》打一个生肖动物,词语解释
浙江12月底全面停工是真的吗(浙江什么时候放假停工)
如何做t(t怎么把p做哭)
北京口碑最差的三甲医院(北京301医院最擅长什么)