这是在c++中启动线程的正确方式吗?

Is this the right way to start a thread in C++

本文关键字:方式吗 线程 启动 c++      更新时间:2023-10-16

这是我用来启动线程的方法,它工作,但我想知道这种方式是否有任何缺点。

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);结尾。

如果你可以访问c++ 11,使用<thread>库,你就不需要担心跨平台兼容性:

#include <thread>
std::thread t(&ThreadFunction, nullptr);

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

t.join();

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

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

对于POSIX,使用pthread_create()