线程被添加到C ++ 11语言
然后我想知道有什么区别,优势和影响?
如果此代码是通过 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
传递single void*
,而std::thread
如果出现问题,则编译时错误,而不是运行时错误std::thread
是一个对象,而不是一个指针,这使得管理对象的生存期更加容易,并降低了指针悬空的风险,尤其是在与指针组合std::unique_ptr
或std::shared_ptr
什至需要指针变戏法的情况下。这些就是想到的直接好处。
至于标准库与语言规范:它们都是同一标准的一部分,因此它们都被视为“ C ++ 11”。请注意,std::thread
可不能在C ++ 03中实现,因为移动语义在C ++的新11和std::thread
工具移动。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句