假设我有这个 big_task()
函数,我可以在线程之间拆分以加快速度。
用多线程解决这个问题的方法是在函数的每个任务上调用 _beginthread()
然后等待所有线程完成,对吧?
我怎么知道这是否有效并真正有益于最小化 big_task()
运行时间?
我还听说多线程效率取决于客户端的平台和硬件。这意味着它也是我需要在我的程序开始时查询的东西......?
还有一个问题,在 Windows 中编码时,使用 CreateThread()
比使用 _beginthread()
更好吗?我编写跨平台应用程序,但如果 CreateThread()
比我可以专门化我的代码以在 Windows 中使用它更有效。
最佳答案
The way to solve that issue with multithreading is to call _beginthread() on each task of the function and then wait for all the threads to finish, right?
这样你就可以并行化你的大函数了,没错。
How do I know if that's gonna be efficient and actually benefit to minimize big_task() running time?
你必须分析它。如果您的大函数在没有 I/O 操作的 CPU 上执行代码,那么请考虑创建与 CPU 内核数相同的线程数。
I also heard that multithreading efficiency depends on the platform and hardware of the client. That means that it's something I need to query in the beginning of my program as well..?
拥有更多核心的 CPU 肯定会比拥有更少核心的 CPU 更快,您可以查看 PPL(仅限 win)、TBB、OpenMP 库,这些库可确保任务根据 CPU 核心数量高效运行。
One more question, when coding in Windows, is it better to use CreateThread() rather than _beginthread()? I write cross platform applications but if CreateThread() is more efficient than I could specialize my code to use that in Windows.
如果你想要跨平台,那么使用 std::thread 或 boost。
关于c++ - 多线程在 C++ 中执行单个任务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33798533/