提升线程死锁,任何人都可以检查原因
boost thread deadlock, can anyone check why?
我试图编写一个可以具有多线程读写的程序。它可以通过一次读取和一次写入正常工作,但是当我使用两次读取和一次写入时,它以死锁告终。
谁能帮忙检查一下?
const int BUF_SIZE = 10;
const int ITERS = 100;
boost::mutex io_mutex;
class buffer
{
public:
typedef boost::mutex::scoped_lock scoped_lock;
buffer() : p(0), c(0), full(0)
{}
void put(int m)
{
scoped_lock lock(mutex);
if (full == BUF_SIZE)
{
{
boost::mutex::scoped_lock lock(io_mutex);
std::cout << "Buffer is full. Waiting..." << std::endl;
}
while (full == BUF_SIZE)
cond.wait(lock);
}
buf[p] = m;
p = (p+1) % BUF_SIZE;
++full;
cond.notify_all();
}
int get()
{
scoped_lock lk(mutex);
if (full == 0)
{
{
boost::mutex::scoped_lock lock(io_mutex);
std::cout << "Buffer is empty. Waiting..." << std::endl;
}
while (full == 0)
cond.wait(lk);
}
int i = buf[c];
c = (c+1) % BUF_SIZE;
--full;
cond.notify_one();
return i;
}
private:
boost::mutex mutex;
boost::condition cond;
unsigned int p, c, full;
int buf[BUF_SIZE];
};
buffer buf;
void writer()
{
for (int n = 0; n < ITERS; ++n)
{
{
boost::mutex::scoped_lock lock(io_mutex);
std::cout << "sending: " << n << std::endl;
}
buf.put(n);
}
}
void reader()
{
for (int x = 0; x < ITERS; ++x)
{
int n = buf.get();
{
boost::mutex::scoped_lock lock(io_mutex);
std::cout << "reader1: received: " << n << std::endl;
}
}
}
int main(int argc, char* argv[])
{
boost::thread thrd1(&reader);
boost::thread thrd2(&writer);
boost::thread thrd3(&reader);
std::string str;
thrd1.join();
thrd2.join();
thrd3.join();
std::getline(std::cin,str);
}
你可能在这里失去了森林。 您的代码写入 ITERS 值,但尝试读取 2 * ITERS 值,因为您有两个读取器。 那行不通。
您至少必须写入 2 * ITERS 值才能完成程序。
相关文章:
- C++映射有2个键,这样任何1个键都可以用来获取值
- 链表c++插入,所有情况都已检查,但没有任何工作
- 是否可以检查悬挂光纤的调用堆栈?
- 任何人都可以告诉我我的 C++ 代码出了什么问题?
- 任何人都可以弄清楚这段代码如何显示运行错误?它打印无限时间 -1 以及正确答案
- 任何人都可以解释一下我是否需要 & 在第一个代码片段中
- 任何人都可以查明我的递归函数中的错误吗?
- 是否有一个库可以检查C++中的变量类型?
- 是否可以检查变量是否位于 L1/L2/L3 缓存中
- 我可以检查初始化列表中设置的构造函数主体中的变量吗
- Qt C++创建一个所有类都可以访问的全局变量
- 任何方法都可以在C++中比较数据结构中的许多方法
- 是否有任何内置函数可以检查给定的两个数字在给定整数数组中的顺序是否相同?
- 是否可以检查给定exception_ptr实例是否拥有某种类型的异常?
- 交叉和计算,任何人都可以解释代码吗?
- 是否有 lint 工具可以检查子类虚拟函数是否与父类定义匹配?
- 我的合并排序没有给出正确的排序数组,任何人都可以解释一下吗?
- 任何人都可以解释这个初始值设定项代码吗?
- 任何人都可以检查这个回文 c++ 代码是否正确
- 提升线程死锁,任何人都可以检查原因