在Linux下,C++可以通過多種方式實現多線程編程。最常用的方法是使用POSIX線程庫(pthread)。以下是一個簡單的示例,展示了如何在C++中使用pthread創建和運行多個線程:
首先,確保你的系統已經安裝了pthread庫。在大多數Linux發行版中,它通常是預裝的。如果沒有,你可以使用包管理器(如apt或yum)來安裝它。
創建一個C++源文件,例如multithread_example.cpp,并添加以下代碼:
#include <iostream>
#include <pthread.h>
// 線程函數原型
void* thread_function(void* arg);
int main() {
pthread_t thread1, thread2;
int result1, result2;
// 創建線程1
result1 = pthread_create(&thread1, NULL, thread_function, (void*)"Thread 1");
if (result1 != 0) {
std::cerr << "Error creating thread 1" << std::endl;
return 1;
}
// 創建線程2
result2 = pthread_create(&thread2, NULL, thread_function, (void*)"Thread 2");
if (result2 != 0) {
std::cerr << "Error creating thread 2" << std::endl;
return 1;
}
// 等待線程1結束
pthread_join(thread1, NULL);
std::cout << "Thread 1 finished" << std::endl;
// 等待線程2結束
pthread_join(thread2, NULL);
std::cout << "Thread 2 finished" << std::endl;
return 0;
}
// 線程函數
void* thread_function(void* arg) {
std::string thread_name = static_cast<const char*>(arg);
std::cout << thread_name << " is running" << std::endl;
// 在這里執行線程任務
return NULL;
}
g++ -o multithread_example multithread_example.cpp -pthread
注意:-pthread選項告訴編譯器鏈接pthread庫。
./multithread_example
這個示例將創建兩個線程,它們將并發運行并輸出它們的名稱。pthread_create函數用于創建線程,pthread_join函數用于等待線程結束。
除了pthread庫之外,C++11還引入了新的線程支持庫(