温馨提示×

如何在ubuntu用c++多线程

小樊
40
2026-09-20 17:06:20
栏目: 编程语言

在 Ubuntu 上使用 C++ 多线程,通常有两种常见方式:

  1. C++11 标准线程(std::thread) ✅(推荐)
  2. POSIX 线程(pthread)(偏底层)

下面以 C++11 std::thread 为主讲,最常用、最现代。


一、环境准备(Ubuntu)

1. 安装编译器

sudo apt update
sudo apt install g++ build-essential

查看版本:

g++ --version

二、最简单的 C++ 多线程示例

示例 1:创建线程

#include <iostream>
#include <thread>

void hello() {
    std::cout << "Hello from thread!" << std::endl;
}

int main() {
    std::thread t(hello);
    t.join();  // 等待线程结束
    return 0;
}

编译(重要:加 -pthread)

g++ main.cpp -o main -pthread

运行:

./main

三、多线程传参

#include <iostream>
#include <thread>

void print(int n, const std::string& s) {
    std::cout << s << ": " << n << std::endl;
}

int main() {
    std::thread t(print, 10, "value");
    t.join();
}

四、多个线程

#include <iostream>
#include <thread>
#include <vector>

void work(int id) {
    std::cout << "Thread " << id << " running\n";
}

int main() {
    std::vector<std::thread> threads;

    for (int i = 0; i < 5; ++i) {
        threads.emplace_back(work, i);
    }

    for (auto& t : threads) {
        t.join();
    }
}

五、线程同步(避免数据竞争)

使用 std::mutex

#include <iostream>
#include <thread>
#include <mutex>

std::mutex mtx;
int counter = 0;

void increment() {
    for (int i = 0; i < 10000; ++i) {
        std::lock_guard<std::mutex> lock(mtx);
        counter++;
    }
}

int main() {
    std::thread t1(increment);
    std::thread t2(increment);

    t1.join();
    t2.join();

    std::cout << "Counter: " << counter << std::endl;
}

六、常见问题

1. 忘记 join()

terminate called without an active exception

✅ 解决:线程结束前必须 join() 或 detach()


2. 忘记 -pthread

undefined reference to `pthread_create`

✅ 编译加:

-pthread

七、pthread 简单示例(可选)

#include <pthread.h>
#include <iostream>

void* run(void*) {
    std::cout << "pthread\n";
    return nullptr;
}

int main() {
    pthread_t t;
    pthread_create(&t, nullptr, run, nullptr);
    pthread_join(t, nullptr);
}

编译:

g++ p.cpp -o p -pthread

八、推荐学习方向

  • std::async
  • std::future
  • 线程池
  • 原子操作 std::atomic

如果你有 具体需求(比如:网络、计算加速、GUI、生产者消费者),我可以给你更针对性的示例。

0 踩