multithreading - c++11线程的优势

标签 multithreading c++11

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/

相关文章:

c++ - 用 "pure"C++11 替代方案替换 BGL 遍历顶点?

java - 实现 Spring ThreadPoolTask​​Executor 并提供最佳的配置值

linux - 使用 Bash 脚本进行多线程编程

c++ - 使用 lambda 作为模板参数时,这个编译器错误是什么?

c++ - 在函数、编译时或运行时创建的数组?

c++ - 斯科特迈耶斯谈右值

Java多线程问题——消费者/生产者模式

c++ - 将写锁降级为读锁时 TMultiReadExclusiveWriteSynchronizer 的行为

Java/Swing 应用程序随机卡住

c++ - 在默认模板参数中调用 constexpr