c++ - 是否可以使函数始终在同一个线程中运行?[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
}
解决方案
foo
可以是实际实现的包装器fooImpl
。foo
会弄清楚它是否可以fooImpl
直接调用,或者它是否必须使用某种同步机制来将所有输入参数提供给永远运行的线程,并触发该线程执行fooImpl
,然后检索输出(如果有的话)。
推荐阅读
- javascript - 我想制作一个不和谐的机器人,以便它可以接收两部分命令。所以如果我说 -count 5,我的机器人会说 6
- c# - Xamarin 形成 Google 身份验证
- python - 从嵌套字典中删除键和值
- java - 为 appium 测试脚本创建独立的 jar
- laravel - 使用 TailwindCSS 在 Laravel 7 中编译 Sass 或 Scss 错误
- php - Laravel 将文件缓存迁移到 redis
- javascript - 如何设置超时以在 Javascript 中使用 if 函数显示多个 div
- sql - Powershell SQL Server Read-SqlTableData 将数字转换为十进制
- api - POT失眠插件安装失败
- javascript - 是否有一种方法可以将 '1234567' 转换为 ['1234', '567', '', '']?