提升两个线程
boost two threads
关于循环的C++Boost问题。
所以我一直在尽可能多地查看信息,但仍然没有看到任何我试图做什么的例子或它的工作原理。
几年来,我一直在业余时间用C++设计游戏。我找到了游戏逻辑的核心引擎,以及一个粗略的输入系统,并使用OpenGL和AL进行输出。我想做的是弄清楚如何启动我的引擎,然后在单独的线程中运行我的输入系统、图形引擎和声音系统。并同时运行。同步我的线程是下一步,但我无法让线程一起运行。
boost::thread gTrd(boost::bind(&game::runGraphics, this));
gTrd.join();
boost::thread sTrd(boost::bind(&game::runSound, this));
sTrd.join();
boost::thread iTrd(boost::bind(&game::runInput, this));
iTrd.join();
boost::thread cTrd(boost::bind(&game::runCore, this));
cTrd.join();
这就是我到目前为止所得到的。据我所见,问题是gTrd中的图形引擎有一个无限循环,它应该一直持续到程序终止,所以我打开了空白屏幕,但它从未启动sTrd。
究竟需要什么来制作它,这样我才能运行理论上不确定的线程?此外,我需要注意的内存泄漏方面的任何潜在问题都非常棒。
你知道join()
是做什么的吗?当您调用它时,它会阻塞主线程,直到调用join的线程完成。在代码中,您启动一个线程,调用join等待它完成,然后启动另一个线程并重复此过程。调用detach()
以允许执行继续(您不在乎线程何时完成执行(,或者在启动所有线程后调用join()
(取决于您的需要(。
注意:只有当您希望等待线程完成执行时,才需要调用join。
一旦希望所有线程停止运行,就应该只join()
所有线程。正如您所说,每个线程都在某种无休止的循环中运行,所以当您在要求线程停止运行之前调用join()
时,您的主线程将永远不会恢复运行。
相反,您应该首先告诉线程您希望它们完成运行。在伪代码中,有一个简单的机制可以做你想做的事:
RunGame()
{
initialize_all_threads(); //just like your sample code does minus the join functions
...//do stuff while game is running
wait_for_quit_signal_from_input_thread(); //note that the input thread is the only thread which transfers messages back to the main thread
//quit signal received, so we should quit game
signal_all_threads_exit(); //via some kind of flag/synchronization object which all thread "main loops" are listening on
join_all_threads(); //wait for threads to gracefully end, perhaps with a timeout
}
为什么不转储所有的join((呢?
boost::thread gTrd(boost::bind(&game::runGraphics, this));
boost::thread sTrd(boost::bind(&game::runSound, this));
boost::thread iTrd(boost::bind(&game::runInput, this));
game::runCore();
相关文章:
- 在两个线程上读/写 64 位,无互斥/锁定/原子
- 如果两个线程相互依赖,则 cpp 线程连接应使用连接导致死锁
- 两个线程一个使用流 Api,另一个线程创建文件失败并出现错误ERROR_SHARING_VIOLATION
- 简单使用 std::atomic 在两个线程之间共享数据
- 如何使用 pthreads 以正确的方式设置两个线程之一的优先级
- 曼德布洛特 从一个线程被反复使用变为两个线程
- C++ 两个线程,共享几个整数变量
- 如何正确同步这两个线程?
- 两个线程尝试将一些数据读/写到数据库中表的同一行中
- 两个线程的公共资源 - 同步足够吗?
- 如果两个线程调用同一个函数,但函数中的所有变量都是局部变量,我还需要担心线程之间共享数据吗?
- 当两个线程同时尝试在同一静音上尝试try_lock()时会发生什么
- C 带有两个线程的boost async_read vs
- 使用 Poco:Condition 唤醒两个线程
- C 两个线程一个用于输入,一个用于输出
- 将两个线程同步到同一个计时器
- 全局变量的最终值,该变量正在通过两个线程进行增量
- C++中两个线程的互斥体
- Qthread char阵列在两个线程之间传递后被摧毁
- 如何使用CPP中使用一个对象运行同一类的两个线程