【发布时间】:2015-06-06 03:43:01
【问题描述】:
我正在进行一项设计,并试图弄清楚如何在多线程应用程序中使用条件变量。我的情况如下所述:
class MyClass1
{
boost::mutex mut;
boost::condition_variable var;
public:
void myfunc1()
{
boost::scoped_lock mylock(mut);
//Wait untill notification is invoked
var.wait(lock);
//Continue processing after waking up
}
void wakeupClass1()
{
//Call notify to wake up only myfunc1
var.notify_one();
}
};
class MyClass2
{
boost::mutex mut;
boost::condition_variable var;
public:
void myfunc2()
{
boost::scoped_lock mylock(mut);
//Wait untill notification is invoked
var.wait(lock);
//Continue processing after waking up
}
void wakeupClass2()
{
//Call notify to wake up only myfunc2
var.notify_one();
}
};
我的问题是,当在wakeupclass1() 中调用notifyone() 时,它会唤醒MyClass2 中的条件变量还是仅限于唤醒Class1 的类范围内的线程,其中声明了第一个条件变量。在代码中,您必须注意每个类中的条件变量具有完全相同的名称。但我的问题是 C++ 语言是否将条件变量的使用限制在声明它的范围内,即在类内。如果这行得通,这段代码设计的优点是每个 Class MyClass1 和 MyClass2 可以在单独的线程中运行,并且当每个类的相应唤醒函数被调用时,只会执行运行该特定类的 myfunc 的线程,这可以非常在多线程应用程序中很有用。
【问题讨论】:
-
这是一个很好的答案。确定哪个线程醒来有点棘手。我正在考虑使用日志语句来区分每个正在唤醒的线程。一旦我尝试就会发布我的发现。还必须注意,唤醒也容易产生虚假信号。因此,在每个编译器实现中,每次唤醒都不是合法的唤醒。
标签: c++ multithreading boost-thread