ubuntu編譯c++時(shí)如何處理多線程問(wèn)題

小樊
81
2024-09-25 07:11:16

在Ubuntu上編譯C++程序時(shí),如果需要處理多線程問(wèn)題,可以使用C++11標(biāo)準(zhǔn)中的<thread>庫(kù)

  1. 包含頭文件:
#include <iostream>
#include <thread>
#include <vector>
#include <mutex>
  1. 定義一個(gè)互斥量,用于同步輸出:
std::mutex mtx;
  1. 編寫一個(gè)可以在線程中執(zhí)行的函數(shù):
void print_numbers(int start, int end) {
    for (int i = start; i <= end; ++i) {
        std::unique_lock<std::mutex> lock(mtx);
        std::cout << "Thread " << std::this_thread::get_id() << ": "<< i << std::endl;
        lock.unlock();
    }
}
  1. main函數(shù)中創(chuàng)建多個(gè)線程并啟動(dòng)它們:
int main() {
    const int num_threads = 4;
    const int numbers_per_thread = 10;

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

    int range = numbers_per_thread * num_threads;
    int step = range / num_threads;

    for (int i = 0; i < num_threads; ++i) {
        int start = i * step + 1;
        int end = (i == num_threads - 1) ? range : (i + 1) * step;
        threads.emplace_back(print_numbers, start, end);
    }

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

    return 0;
}
  1. 使用g++編譯器編譯代碼:
g++ -std=c++11 -pthread your_source_file.cpp -o output_binary

在這個(gè)示例中,我們創(chuàng)建了一個(gè)可以在線程中運(yùn)行的函數(shù)print_numbers,并在main函數(shù)中創(chuàng)建了多個(gè)線程來(lái)執(zhí)行這個(gè)函數(shù)。我們還使用了互斥量mtx來(lái)同步輸出,確保在同一時(shí)間只有一個(gè)線程可以訪問(wèn)std::cout

注意,我們?cè)诰幾g時(shí)添加了-std=c++11-pthread選項(xiàng)。-std=c++11告訴編譯器我們使用的是C++11標(biāo)準(zhǔn),而-pthread選項(xiàng)告訴編譯器鏈接線程庫(kù)。

0