溫馨提示×

c++ cout如何實現多線程輸出

c++
小樊
126
2024-08-13 00:39:40
欄目: 編程語言

在C++中,可以使用std::mutex來實現多線程輸出。std::mutex是C++11標準引入的線程同步原語,可以用來保護共享資源,防止多個線程同時訪問。

下面是一個使用std::mutex來實現多線程輸出的示例代碼:

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

std::mutex g_mutex;

void printHello(int threadID) {
    // 加鎖
    std::lock_guard<std::mutex> lock(g_mutex);
    
    // 輸出
    std::cout << "Hello from thread " << threadID << std::endl;
}

int main() {
    std::thread t1(printHello, 1);
    std::thread t2(printHello, 2);
    
    t1.join();
    t2.join();
    
    return 0;
}

在上面的示例代碼中,我們定義了一個printHello函數來輸出線程的ID。在函數中我們使用std::lock_guard<std::mutex>來對g_mutex進行加鎖,確保多個線程不會同時訪問std::cout,從而避免輸出混亂的情況。

main函數中,我們創建了兩個線程t1t2,分別調用printHello函數輸出線程的ID。最后通過調用t1.join()t2.join()來等待線程執行完畢。

通過這種方式,我們可以實現多線程輸出,確保輸出的順序是正確的。

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