I tried to write a program that can have mutiple-threaded reads and writes. It works fine with one read and one write, but it ended in deadlock when I use two reads and one write.
我试着编写一个可以进行多线程读写的程序。它可以在一次读取和一次写入时正常工作,但是当我使用两次读取和一次写入时,它以死锁结束。
Can anyone help to check?
任何人都可以帮助检查?
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);
}
1 个解决方案
#1
5
You possibly lost the forest for the trees a bit here. Your code writes ITERS values but tries to read 2 * ITERS values since you have two readers. That can't work.
你可能在这里失去了森林的树木。您的代码写入ITERS值但尝试读取2 * ITERS值,因为您有两个读取器。那不行。
You'll at least have to write 2 * ITERS values to get the program to complete.
您至少必须编写2 * ITERS值才能完成程序。
#1
5
You possibly lost the forest for the trees a bit here. Your code writes ITERS values but tries to read 2 * ITERS values since you have two readers. That can't work.
你可能在这里失去了森林的树木。您的代码写入ITERS值但尝试读取2 * ITERS值,因为您有两个读取器。那不行。
You'll at least have to write 2 * ITERS values to get the program to complete.
您至少必须编写2 * ITERS值才能完成程序。