在Linux中,C++多線程可以通過POSIX線程庫(pthread)來實現。以下是一個簡單的示例,展示了如何使用pthread創建和運行多個線程:
#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;
if (pthread_create(&threads[i], nullptr, thread_function, &thread_ids[i]) != 0) {
std::cerr << "創建線程失敗" << std::endl;
return 1;
}
}
// 等待線程結束
for (int i = 0; i < num_threads; ++i) {
pthread_join(threads[i], nullptr);
}
std::cout << "所有線程已結束" << std::endl;
return 0;
}
要編譯這個程序,你需要鏈接pthread庫。在命令行中,可以使用以下命令:
g++ -o multi_thread_example multi_thread_example.cpp -lpthread
然后運行生成的可執行文件:
./multi_thread_example
這個示例創建了5個線程,每個線程都會打印其線程ID。注意,線程的執行順序是不確定的,因此輸出的順序可能會有所不同。
在實際應用中,你可能需要使用互斥鎖(mutex)、條件變量(condition variable)等同步原語來確保線程之間的正確同步。這些同步原語也提供了在pthread庫中。