首页 > 解决方案 > 是否可以使函数始终在同一个线程中运行?[C++]

问题描述

简单示例,您有两个函数,foo 和 baz。Baz 打电话给 foo。即使 baz 是从单独的线程启动的,您可以运行它在主线程中调用的 foo 吗?

int foo(int Z)
{
    cout << Z;
    return 0;
}

int baz(int Z)
{
   return foo(-Z);
}


int main()
{
   
   foo(6); // foo is run in main thread
   baz(6); // baz is run in main thread
  thread th2(baz,7); // baz is run in thread 2, but its call to foo is run in the main thread

}

标签: c++multithreading

解决方案


foo可以是实际实现的包装器fooImplfoo会弄清楚它是否可以fooImpl直接调用,或者它是否必须使用某种同步机制来将所有输入参数提供给永远运行的线程,并触发该线程执行fooImpl,然后检索输出(如果有的话)。


推荐阅读