Linux 中的 C++ 线程

标签 c++ linux multithreading

<分区>

我正在尝试在 Linux 中创建多线程 C++ 程序。我以前在 Windows 上使用过 pthreads 库,但我听说它不是 Linux 的标准。对于 C++ 和 Linux,您建议使用什么线程库?有哪些选择,最常见的是什么,通常最快的是什么?谢谢!

编辑:我误以为 pthreads 不是 linux 原生的,正如我所说,这是我不久前听到的。我主要是想比较各种线程选项的效率,并且特别好奇关于 c-11 线程库与我之前使用的 pthreads 的性能对比的信息。我被误导了,我发布了这个问题以获取更多信息。没必要刻薄。

最佳答案

如果您使用的是 C++11,只需使用 std::thread。这样做相当简单。例如:

#include <thread>

void thread_entry(int foo, int bar)
{
    int result = foo + bar;
    // Do something with that, I guess
}


// Elsewhere in some part of the galaxy
std::thread thread(thread_entry, 5, 10);
// And probably
thread.detach();

// Or
std::thread(thread_entry).detach();

它很简单并且应该足以满足大多数目的(尽管取决于实现,它可能取决于 pthreads)。

如果没有,就使用 pthreads,因为你很熟悉它。它是 POSIX 标准的一部分,大多数 Linux 发行版基本上都符合该标准 — 至少,它们足够符合标准,任何差异对您来说都无关紧要。

关于Linux 中的 C++ 线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17004290/

相关文章:

c# 调用Monitor.Pulse()时抛出对象同步错误

c - 如何阻塞信号量直到其值为正数

c++ - CAtlList::RemoveAt 是否会使现有位置无效?

c++ - 在一行上流式传输多个变量?

c++ - STL 允许使用指向不同 map 的迭代器删除 map 的键/值吗?

c++ - C/C++ 相当于 C# System.Net.Mail

php - 传入/传出电子邮件下载和处理,服务器端

linux - 仅将 docker 镜像绑定(bind)到特定的 MAC 地址

java - 收集特定时间范围内的 JVM GC 样本

c# - 如何使 Backgroundworker 中的进程在取消挂起事件时退出