【问题标题】:boost two threads提升两个线程
【发布时间】:2013-02-16 22:52:58
【问题描述】:

关于循环的 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。

究竟需要什么才能运行我的线程,这些线程理论上是无限线程?此外,我需要注意的内存泄漏方面的任何潜在问题都很棒。

【问题讨论】:

  • 似乎runGraphicsrunSoundrunInput 等应该同时运行,但是您正在等待每个都以.join() 结束,然后再开始下一个。您可能只想在启动所有线程后调用.join()

标签: c++ multithreading boost boost-thread


【解决方案1】:

你知道join() 做什么吗?当你调用它时,它会阻塞主线程,直到调用 join 的线程完成。在您的代码中,您启动一​​个线程,调用 join 以等待它完成,然后启动另一个线程并重复此过程。要么调用detach() 以允许继续执行(并且您不在乎线程何时完成执行),或者在启动所有线程后调用join()(取决于您的需要)。

注意:你只想等到线程完成执行时才调用join。

【讨论】:

  • TY 据我所知, detach() 语句有效。仍然非常骨架结构,感谢您提供有关功能差异的信息。
【解决方案2】:

你应该只在你期望它们停止运行时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

}

【讨论】:

    【解决方案3】:

    为什么不直接转储所有的 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();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-06-07
      • 2011-06-08
      • 2018-07-03
      • 2011-06-18
      • 2012-05-16
      • 2010-11-05
      • 2012-08-15
      相关资源
      最近更新 更多