溫馨提示×

C++中Linux多線程怎樣實現

小樊
39
2025-02-20 05:45:51
欄目: 編程語言

在C++中,Linux平臺下可以使用POSIX線程庫(pthread)來實現多線程。以下是一個簡單的示例,展示了如何創建和運行多個線程:

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

// 線程函數
void* thread_function(void* arg) {
    int thread_id = *(static_cast<int*>(arg));
    std::cout << "線程 " << thread_id << " 正在運行" << std::endl;
    return nullptr;
}

int main() {
    const int num_threads = 5;
    pthread_t threads[num_threads];
    int thread_ids[num_threads];

    // 創建線程
    for (int i = 0; i < num_threads; ++i) {
        thread_ids[i] = i;
        if (pthread_create(&threads[i], nullptr, thread_function, &thread_ids[i]) != 0) {
            std::cerr << "創建線程失敗" << std::endl;
            return 1;
        }
    }

    // 等待線程結束
    for (int i = 0; i < num_threads; ++i) {
        pthread_join(threads[i], nullptr);
    }

    std::cout << "所有線程已結束" << std::endl;
    return 0;
}

要編譯這個程序,請使用以下命令:

g++ -o multi_thread_example multi_thread_example.cpp -pthread

然后運行生成的可執行文件:

./multi_thread_example

這個示例中,我們創建了5個線程,每個線程都會打印其線程ID。注意,在實際應用中,你可能需要處理線程同步、互斥等問題,以避免競爭條件和數據不一致。在這種情況下,可以使用互斥鎖(pthread_mutex_t)和其他同步原語。

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