Threads are added to C++11 language
那我想知道有什么区别、优势和影响?
如果这段代码是由 c++03
#include <iostream>
#include <pthread.h>
void *call_from_thread(void *)
{
std::cout << "Launched by thread" << std::endl;
return NULL;
}
int main()
{
pthread_t t;
pthread_create(&t, NULL, call_from_thread, NULL);
pthread_join(t, NULL);
return 0;
}
还有这个c++11
#include <iostream>
#include <thread>
void call_from_thread()
{
std::cout << "Hello, World" << std::endl;
}
int main()
{
std::thread t1(call_from_thread);
t1.join();
return 0;
}
那么,我看不出根本优势。
此外,当它被称为语言的一部分时,我对此感到困惑,因为我没有看到新的关键字或新的语法。我刚刚看到一个新的标准库。是不是超出了这个范围?这只是 pthread
的释义吗?
最佳答案
除了更便于移植之外,C++11 线程还提供其他好处:
- 允许以类型安全的方式将参数(和多个)传递给线程处理程序。
pthread_create
通过单个void*
, 而std::thread
如果出现问题而不是运行时错误,则会出现编译时错误 - 线程处理程序可以是 lambda
- 一个
std::thread
是一个对象,而不是一个指针,这使得管理对象生命周期更容易,并降低悬空指针的风险,尤其是与std::unique_ptr
结合使用时或std::shared_ptr
如果甚至需要指针杂耍。
这些是我想到的直接好处。
至于标准库与语言规范:它们都是同一标准的一部分,因此它们都被认为是“C++11”。请注意 std::thread
不能在 C++03 中实现,因为移动语义在 C++11 和 std::thread
中是新的实现移动。
关于multithreading - c++11线程的优势,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52272399/