C++ 11 std :: thread vs windows CreateThread

KaM*_*LuS 13 c++ windows multithreading visual-c++

哪个选项是在Visual C++创建(和管理)的线程更好的:C++ 11 std::threadWinAPI功能(如CreateThread,_beginthreadex等),为什么?

mil*_*bug 36

可移植性

std::thread是C++ 11标准的新手 - 有了它,您可以在支持C++ 11的编译器中用C++编写可移植代码.你可以感受到future它.

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

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

CreateThread特定于WinAPI,这意味着编写非可移植代码.此外,这个API很老,使用起来也不方便.

RAII

WinAPI是一个C API,它不鼓励现代C++ 良好 实践.您创建的每个线程原语,您必须稍后手动销毁.

对于C++ 11中的线程库,情况并非如此,这使得更高级别的抽象更容易编写.虽然std::thread仍然相当低级(无论是您.join().detach()您的线程,还是线程析构函数将终止您的程序),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);
Run Code Online (Sandbox Code Playgroud)

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

  • 感受'未来',哈哈. (10认同)
  • @GetFree [需要引用] (2认同)

Pup*_*ppy 7

跨平台性是一个小好处.真正的好处在于界面.std::thread提供关于线程清理的RAII保证,并支持任意函数对象参数而不仅仅是函数指针.std::thread是CreateThreadEX上的C++ 11包装器,出于某种原因,它就是这种方式.

正如旁注,std :: thread是一个可怕的,糟糕的API.如果你自己创建线程,那么你可能做错了.使用真正的线程API,如英特尔的TBB或微软的PPL,它们远远超过了可怕的 std::thread,甚至更糟糕的 CreateThreadEx.std::thread就像,"嘿伙计们,我为你提供了跨平台的服务mmap,所以你可以自己编写malloc,享受!".

  • 好吧,我宁愿在`mmap`之上创建自己的`malloc`,而不仅仅是拥有`malloc`并试图破解它上面的`mmap`.低水平并不可怕.没有低级别的东西,我们永远不会有好的高级功能 (2认同)
  • `std::thread` 甚至不是 RAII 类(至少不是经典意义上的):它的析构函数不会清理线程 - 它会终止程序。 (2认同)