boost多线程一个奇怪的问题,有点搞不明白

u011191275 u011191275 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区
代码是这样的:

#include <iostream>
#include <boost/thread.hpp>
using namespace std;
#include "windows.h"


class TestA
{
public:
TestA(int x)
{
cout << "new TestA()" << endl;
x_ = x;
}

int GetX()
{
return x_;
}

void SetX(int x)
{
x_ = x;
}

private:
int x_;
};


class TestVC
{
public:

TestVC()
{
running_flag = true;
}

void stop()
{
running_flag = false;
{
boost::recursive_mutex::scoped_lock lock(mtx);
cond.notify_all();
}
}

void waitSignalThread(TestA& texta)
{
boost::recursive_mutex::scoped_lock lock(mtx);
while(running_flag)
{
// cout << "start wait signal" << endl;
cond.wait(mtx);
cout << "texta x value is : " << texta.GetX() << endl;
// cout << "finish wait signal" << endl;
}
}

void emitSignalThread(TestA& texta)
{
int i = 100;
while (running_flag)
{
{
boost::recursive_mutex::scoped_lock lock(mtx);
cout << "start emit singal" << endl;
texta.SetX(i--);
// cout << "texta x value is : " << texta.GetX() << endl;
cond.notify_one();
Sleep(100);
cout << "finish emit signal" << endl;
}
}
}

private:

bool running_flag;
boost::recursive_mutex mtx;
boost::condition_variable_any cond;

};


int main()
{
boost::thread_group grp;
TestVC test;
TestA testa(0);

grp.create_thread(boost::bind(&TestVC::waitSignalThread, &test, boost::ref(testa)));
grp.create_thread(boost::bind(&TestVC::emitSignalThread, &test, boost::ref(testa)));

// test.stop();
grp.join_all();

return 0;
}


奇怪的是emitSignalThread中的texta.SetX(i--);执行了N多次,waitSignalThread才会执行一次?
但我换成cout << "start wait signal" << endl;、cout << "finish wait signal" << endl;这样的语句,就只执行一次了?

这是什么问题?很奇怪啊 这!不合逻辑啊!
...全文

相关推荐

评论 3
收藏 已收藏
分享
返回顶部
u011191275
C++ 语言 65,212 成员 250,513 内容