在Linux環境下使用C++實現多線程,通常會使用POSIX線程庫(pthread)。以下是一個簡單的示例,展示了如何創建和使用多線程。
首先,確保你的編譯器支持C++11或更高版本,因為從C++11開始,標準庫也提供了線程支持(<thread>
頭文件),但是這里我們使用的是POSIX線程庫。
#include <iostream>
#include <pthread.h>
void* thread_function(void* arg) {
int thread_id = *(static_cast<int*>(arg));
std::cout << "Thread " << thread_id << " is running." << std::endl;
// 執行一些任務...
pthread_exit(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 << "Error: unable to create thread "<< i << std::endl;
return 1;
}
}
// 等待線程結束
for (int i = 0; i < num_threads; ++i) {
pthread_join(threads[i], nullptr);
}
std::cout << "All threads have finished." << std::endl;
return 0;
}
使用g++編譯器,你可以使用-pthread
選項來鏈接pthread庫:
g++ -pthread -o my_multithreaded_app my_multithreaded_app.cpp
./my_multithreaded_app
這個例子中,我們創建了5個線程,每個線程都會執行thread_function
函數,并打印出自己的線程ID。然后主線程會等待所有子線程完成后才退出。
請注意,多線程編程需要注意線程同步和數據共享的問題,以避免競態條件和數據不一致等問題。在實際應用中,可能需要使用互斥鎖(mutexes)、條件變量(condition variables)等同步機制來保護共享資源。