溫馨提示×

c++多線程在linux怎樣

小樊
97
2024-12-04 01:21:38
欄目: 編程語言

在Linux環境下使用C++進行多線程編程,可以使用C++標準庫中的 <thread>頭文件提供的線程支持

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

void print_block(int n, char c) {
    for (int i = 0; i < n; ++i) {
        std::cout << c;
    }
    std::cout << '\n';
}

int main() {
    const int num_threads = 4;
    const int block_size = 5;

    std::vector<std::thread> threads;

    // 創建線程
    for (int i = 0; i < num_threads; ++i) {
        threads.emplace_back(print_block, block_size, '*');
    }

    // 等待所有線程完成
    for (auto& t : threads) {
        t.join();
    }

    return 0;
}

在這個示例中,我們創建了4個線程,每個線程打印5個星號。std::thread對象表示一個線程,emplace_back函數用于將線程對象添加到threads向量中。join()函數用于等待線程完成。

除了使用std::thread,你還可以使用C++標準庫中的其他同步原語,如互斥鎖(std::mutex)、條件變量(std::condition_variable)和原子操作(std::atomic),以實現更復雜的線程同步和數據共享。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女