在Linux下,C++可以使用POSIX線程庫(pthread)來實現多線程。以下是一個簡單的示例,展示了如何在C++中使用pthread創建和管理線程:
-pthread參數,例如:g++ -std=c++11 -pthread your_file.cpp -o your_program
multithreading_example.cpp,并包含以下代碼:#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;
int result = pthread_create(&threads[i], nullptr, thread_function, &thread_ids[i]);
if (result != 0) {
std::cerr << "創建線程失敗,錯誤代碼:" << result << std::endl;
return 1;
}
}
// 等待線程結束
for (int i = 0; i < num_threads; ++i) {
pthread_join(threads[i], nullptr);
}
std::cout << "所有線程已完成。" << std::endl;
return 0;
}
在這個示例中,我們定義了一個名為thread_function的線程函數,它接受一個void*類型的參數。我們創建了5個線程,每個線程都運行thread_function函數,并傳遞一個線程ID作為參數。然后,我們使用pthread_join函數等待所有線程完成。
g++ -std=c++11 -pthread multithreading_example.cpp -o multithreading_example
./multithreading_example
程序將創建5個線程并輸出它們的ID。當所有線程完成后,程序將輸出"所有線程已完成。"。
這只是一個簡單的示例,實際應用中可能需要使用互斥鎖、條件變量等同步原語來確保線程安全。