溫馨提示×

c++多線程在linux應用

c++
小樊
104
2024-12-04 02:11:39
欄目: 編程語言

在Linux應用中使用C++多線程,你可以使用C++11標準庫中的<thread>頭文件

#include <iostream>
#include <thread>

void print_hello() {
    std::cout << "Hello from thread " << std::this_thread::get_id() << std::endl;
}

int main() {
    // 創建兩個線程
    std::thread t1(print_hello);
    std::thread t2(print_hello);

    // 等待線程完成
    t1.join();
    t2.join();

    return 0;
}

在這個示例中,我們創建了兩個線程t1t2,它們都執行print_hello函數。std::this_thread::get_id()函數用于獲取當前線程的ID。

要在Linux上編譯這個程序,你需要使用支持C++11的編譯器,例如g++。使用以下命令編譯程序:

g++ -std=c++11 -pthread your_source_file.cpp -o your_executable

注意,我們在編譯命令中添加了-std=c++11-pthread選項。-std=c++11告訴編譯器使用C++11標準,而-pthread選項啟用了多線程支持。

編譯完成后,你可以運行生成的可執行文件:

./your_executable

這將輸出類似以下內容:

Hello from thread 1234567890
Hello from thread 9876543210

這里,你可以看到兩個線程分別打印了不同的消息。這就是如何在Linux應用中使用C++多線程的基本方法。

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