【发布时间】:2016-12-27 13:56:18
【问题描述】:
我想在一个类的不同实例之间共享一个互斥体,其函数作为线程运行。我写的方法好吗? (我认为我不需要使用 shared_mutex,尽管这可能是更好的做法。我会以同样的方式传递它吗?)
class A
{
public:
// Execute some work that locks some piece of data by acquiring the mutex.
void execute(std::mutex & myMutex);
}
class B
{
public:
void execute(std::shared_ptr<A> a)
{
// Create the Threads for execution.
// Changed to correct syntax.
std::thread t1(&B::runThread, this, a);
std::thread t2(&B::runThread, this, a);
t1.join();
t2.join();
};
void runThread(std::shared_ptr<A> a)
{
a->execute(std::ref(theMutex));
}
private:
// The Mutex to share with the threads.
std::mutex theMutex;
}
【问题讨论】:
-
为什么不让线程(函数)成为类的成员呢?
-
我进行了编辑以使用例更清晰,但本质上我想从 A 类派生并稍后将其传递。然后 A 的派生类可以使用它认为合适的互斥锁。
标签: c++ multithreading c++11 thread-safety mutex