这个程序里有几个消费者,几个生产者??

wzuxian2012 2012-07-09 11:12:25



代码里 只有2个线程(不算主线程在内)在运行


writer, reader内部是 用了for循环,循环次数各自是100,

这是100个消费者,100个生产者呢 还是1个生产者,1个消费者???

概念很混乱。



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) //100次
{
{
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) //100次
{
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;
}




...全文
47 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
wzuxian2012 2012-07-09
  • 打赏
  • 举报
回复


mfc板块不讨论boost技术吗
wzuxian2012 2012-07-09
  • 打赏
  • 举报
回复
reader, write中的循环都去掉

改成:

boost::thread w_thread[100];
boost::thread r_threa[100];

for(i=0; i<100 ;i ++)
{

w_thread[i].函数(write);
r_thread[i].函数(read);

}

会怎样???





[Quote=引用楼主 的回复:]
C/C++ code




代码里 只有2个线程(不算主线程在内)在运行


writer, reader内部是 用了for循环,循环次数各自是100,

这是100个消费者,100个生产者呢 还是1个生产者,1个消费者???

概念很混乱。



const int BUF_SIZE = 10;
const int ITERS = 100;

boos……
[/Quote]
wzuxian2012 2012-07-09
  • 打赏
  • 举报
回复
已经找到答案了,可以结贴

15,471

社区成员

发帖
与我相关
我的任务
社区描述
VC/MFC 进程/线程/DLL
社区管理员
  • 进程/线程/DLL社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧