gpt4 book ai didi

c++ - 这是在 C++ 中启动线程的正确方法吗

转载 作者:太空宇宙 更新时间:2023-11-04 15:01:15 25 4
gpt4 key购买 nike

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

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 上)或 beginthreadex .

对于 POSIX,使用 pthread_create() .

关于c++ - 这是在 C++ 中启动线程的正确方法吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40154591/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com