各位大神好,
小弟最近剛剛開始學習boost 的thread庫,看了資料有個關于條件變數的問題不太明白
源代碼如下:
#include <boost/thread/thread.hpp>
#include <boost/thread/mutex.hpp>
#include <boost/thread/condition.hpp>
#include <iostream>
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_one();
}
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 << "received: "
<< n << std::endl;
}
}
}
int main(int argc, char* argv[])
{
boost::thread thrd1(&reader);
boost::thread thrd2(&writer);
thrd1.join();
thrd2.join();
return 0;
}
上面這段代碼中,執行緒thrd1 的reader函式先呼叫buffer這個類的成員函式get(),所以會先列印出 "Buffer is empty. Waiting...",thrd2先列印sending:0 也沒有問題,接下來thrd1 在條件變數那里被阻塞,因此thrd2 會呼叫burffer的函式put(),但是隨著put()函式最后的notify_one()重新喚醒,reader()函式不是應該接下來列印"received: 0“ 這句話嗎?為什么還是會繼續列印sending:2這句話呢?
uj5u.com熱心網友回復:
擦,一個回復都沒有轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/88635.html
標籤:基礎類
上一篇:qiuzhu
