在Ubuntu上編譯C++程序時(shí),如果需要處理多線程問(wèn)題,可以使用C++11標(biāo)準(zhǔn)中的<thread>
庫(kù)
#include <iostream>
#include <thread>
#include <vector>
#include <mutex>
std::mutex mtx;
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();
}
}
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;
}
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ù)。