使用多个使用者线程时崩溃
crashed when using multiple consumer thread
只有一个消费者工作正常,但多个消费者会崩溃,我想知道为什么。
#include <iostream>
#include <string>
#include <vector>
#include <pthread.h>
#include <unistd.h>
#include <queue>
using namespace std;
pthread_mutex_t g_mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t g_qs_notempty = PTHREAD_COND_INITIALIZER;
pthread_cond_t g_qs_notfull = PTHREAD_COND_INITIALIZER;
queue<string> qs;
void *
producer(void *arg)
{
static vector<string> vs{"a ","b ","c ","d ","e "};
static int idx = 0;
while(1){
pthread_mutex_lock(&g_mutex);
if(qs.size()==5)//full
pthread_cond_wait(&g_qs_notfull,&g_mutex);
qs.push(vs[idx]);
idx = (idx+1)%5;
pthread_cond_signal(&g_qs_notempty);
pthread_mutex_unlock(&g_mutex);
}
return NULL;
}
void *
consumer(void *arg)
{
while(1){
pthread_mutex_lock(&g_mutex);
if(qs.empty())
pthread_cond_wait(&g_qs_notempty,&g_mutex);
cout<<qs.front();
qs.pop();
pthread_cond_signal(&g_qs_notfull);
pthread_mutex_unlock(&g_mutex);
}
return NULL;
}
int main()
{
struct thread_info *tinfo;
pthread_attr_t attr;
pthread_t thread_id;
pthread_attr_init(&attr);
pthread_create(&thread_id, &attr, &producer, 0);
pthread_create(&thread_id, &attr, &consumer, 0);
pthread_create(&thread_id, &attr, &consumer, 0); //adding this line will crash
pthread_exit(0);
}
不能保证_signal()
只唤醒一个线程。
所以你必须在醒来后重新检查你的情况。修复代码的一个简单方法是将if
切换为while
。
相关文章:
- CoInitialize()在单独的线程上崩溃而不返回
- 为什么我的多线程作业队列崩溃
- C/C++ Linux 上的多线程服务器/客户端崩溃
- ZeroMQ 在使用 std::thread 创建工作线程时崩溃
- 使用-static libstdc++时std::线程弱,因此在运行时会导致崩溃
- Qt-工作线程崩溃时将cv::Mat转换为QImage
- 在官方 ZeroMQ 多线程示例的修改版本中崩溃
- 在提升时不一致崩溃::线程::release_handle?
- C 多线程崩溃应用程序
- 在 Unity 中C++使用后台线程进行图像处理会导致崩溃
- C++线程的向量在连接时随机崩溃
- Malloc()/free()在Windows上的几个线程中崩溃
- 使用多线程崩溃
- C++多线程应用程序崩溃
- CUDA内核无缘无故地使用20K 线程崩溃
- Qopenglwidget将上下文移至另一个线程崩溃
- 使用QT和QOGL的多线程崩溃
- 复制提升::跨线程崩溃的异常
- 释放模式下的boost线程崩溃
- 退出时分离的线程崩溃