【问题标题】:Is this the right way to start a thread in C++这是在 C++ 中启动线程的正确方法吗
【发布时间】:2017-03-02 11:07:02
【问题描述】:

这是我用来启动线程的方法,它有效,但我想知道这种方法有什么缺点。

void myFunc()
{
    //code here

}


unsigned int _stdcall ThreadFunction(void* data)
{
    myFunc();
    return 0;
}

我使用的主要功能:

HANDLE A = (HANDLE)_beginthredex(0,0,&ThreadFunction,0,0,0);

我以CloseHandle(A); 结束话题。

【问题讨论】:

  • #include <thread>。使用 C++ STL 的 thread 库。

标签: c++ multithreading


【解决方案1】:

如果您可以访问 C++11,请使用 <thread> 库,您无需担心跨平台兼容性:

#include <thread>

std::thread t(&ThreadFunction, nullptr);

要等待线程执行完成,请使用join():

t.join();

这会阻塞,直到线程应该运行的函数返回。

否则,请使用 CreateThread(因为它看起来像是在 Windows 上)或 beginthreadex。

对于 POSIX,使用 pthread_create()。

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-02-23
  • 2013-07-20
  • 2013-03-24
  • 2014-02-21
相关资源
最近更新 更多