【发布时间】:2020-12-01 10:03:52
【问题描述】:
我有一个类,它的一些函数是线程安全的。
class A
{
public:
// Thread Safe class B
B foo;
// Thread specific class C
C bar;
void somefunc()
{
// uses foo and bar
}
}
class C
{
public:
C()
{
m_id = std::this_thread::get_id();
}
// id of the thread which created the class
std::thread::id m_id;
}
A 类可以设置在不同的线程上。由于 C 类是线程特定的,我想从线程 m_id 运行 somefun。
所以我想通过将 somefun 提交给 m_id 标识的线程来执行 somefun。
主要问题是,如果我知道线程的线程 ID,我能否在活动线程上运行特定函数?
【问题讨论】:
-
不是很清楚,因为C既是类型又是bar类型的变量...请给minimal reproducible example
-
对不起,我在输入问题时搞砸了
-
您能告诉我们您如何创建线程以及它们如何共享
A的实例吗? -
还是很模糊。线程安全吗?线程如何拥有A的对象?你让你的例子如此抽象以至于很难理解。更大的图景是什么?
-
thread_local C bar;确保bar是线程特定的。
标签: c++ multithreading c++14