c++ 多线程: 请问为什么我在主线程里使用条件变量唤醒子线程没有反应,子线程不打印信息
#include <iostream>
#include <thread>
#include <mutex>
#include <vector>
#include <Windows.h>
using namespace std;
mutex mymutex;
condition_variable mCond;
bool f = false;
class Thread { // 自定义线程类
public:
typedef void (*CallBackFunc) (void*);
bool start(void* arg);
bool detach();
bool join();
thread::id id;
Thread() :mArg(nullptr), mIsStart(false), mIsDetach(false) {};
Thread(CallBackFunc c) :mArg(nullptr), mIsStart(false), mIsDetach(false), c(c) {};
~Thread();
void handle(void* arg) { c(arg); };
private:
void run(void* arg);
void* threadRun(void*);
void* mArg;
bool mIsStart;
bool mIsDetach;
thread mThreadId;
CallBackFunc c;
};
bool Thread::start(void* arg)
{
mArg = arg;
mThreadId = thread(&Thread::threadRun, this, this);
mIsStart = true;
id = this_thread::get_id();
return true;
}
bool Thread::detach()
{
if (!mIsStart) { return false; }
if (mIsDetach) { return true; }
mThreadId.detach();
mIsDetach = true;
return true;
}
bool Thread::join()
{
if (!mIsStart || mIsDetach) { return false; }
mThreadId.join();
return true;
}
Thread::~Thread()
{
if (mIsStart && !mIsDetach) { detach(); }
}
void* Thread::threadRun(void* arg)
{
Thread* t = (Thread*)arg;
t->run(t->mArg);
return nullptr;
}
void Thread::run(void* arg) {
handle(arg);
}
void action1(void* arg) {
while (!f)
{
unique_lock<mutex> sb(mymutex);
mCond.wait(sb, [&]() {
return f;
});
int* x = (int*)arg;
cout << "thread id: " << this_thread::get_id() << " x: " << x << endl;
}
}
int main() {
int x = 1;
vector<Thread*> v;
for (int i = 0; i < 5; i++) {
v.push_back(new Thread(action1));
v[i]->start((void*)x++);
}
while (true)
{
f = !f;
mCond.notify_one();
Sleep(1000);
}
return 0;
}