C++11 std::thread vs windows CreateThread

标签 c++ windows multithreading visual-c++

哪个选项更适合在 Visual C++ 下创建(和管理)线程:C++11 std::threadWinAPI 函数(例如 CreateThread _beginthreadex 等)以及为什么?

最佳答案

便携性

std::thread 是 C++11 标准的新内容 - 使用它,您可以在支持 C++11 的编译器之间用 C++ 编写可移植代码。你可以在其中感受到 future

它基于 boost::thread,它支持不支持 C++11 的旧编译器 - 这使得移植到其他平台更加容易。

如果您需要使用特定平台的技巧,std::thread::native_handle是要走的路。

CreateThread 特定于 WinAPI,这意味着编写不可移植的代码。另外,这个 API 比较老旧,使用起来比较不方便。

RAII

WinAPI 是一个 C API,不支持现代的 C++ good practices .您创建的每个线程原语,您必须在以后手动销毁。

C++11 中的线程库并非如此,这使得更高级的抽象更易于编写。虽然 std::thread 仍然相当低级(您的 .join().detach() 您的线程,或者线程destructor 将终止您的程序),C++11 线程库具有 std::lock_guard 和其他锁类,用于支持互斥锁的 RAII。

虽然 C++11 有一些更高级别的抽象,例如用于异步启动函数的 std::async,但它不提供线程池等其他抽象,因此您可能需要使用其他库。

类型安全

WinAPI 只能调用具有特定签名的函数指针 - 这很容易出现与类型安全、对象生命周期和内存管理不善相关的错误。

std::thread 可以调用任何可调用对象:

// call free-standing function in a separate thread
std::thread first(func);

// call free-standing function with arguments (1, 2), in a separate thread
std::thread second(func, 1, 2); 

// call static member function in a separate thread
std::thread third(&A::static_memfun); 

// call non-static member of a temporary in a separate thread
std::thread fourth(&A::memfun, A());

//call std::function in a separate thread
std::function<void(int)> callback = std::bind(func, 1, _1);
std::thread fifth(callback, 2);

// call a function object
Functor f;
std::thread sixth(f);

TL;DR:没有理由在新的 C++ 代码中使用 WinAPI 线程作为主线程机制。

关于C++11 std::thread vs windows CreateThread,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25221247/

相关文章:

C++ - char* 与 string*

c++ - 相同的 C++ 代码导致 Windows 上的无限循环和 OSX 上的预期行为

c# - 使用 ADO.Net 多线程访问 MySQL

.net - 线程优先级

c++ - 如何从字符串中获取数字?

c++ - 这段代码使用复制构造函数时出错 - C++08

java - Torrent 库允许下载单独的文件片段

c++ - 为什么在调试过程中有时窗口标题黑色和按钮无框

windows - Mac 设置以在每种可能的浏览器中测试应用程序?

python - 如何杀死这个threading.Timer?