在Linux環境下,C++可以通過POSIX線程庫(pthread)來實現多線程編程。以下是一個簡單的示例,展示了如何在C++中使用pthread創建和管理線程:
首先,確保你的系統已經安裝了pthread庫。在大多數Linux發行版中,它已經是默認安裝的。
創建一個名為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: pthread_create failed for thread 1" << std::endl;
return 1;
}
// 創建線程2
result2 = pthread_create(&thread2, NULL, thread_function, (void*)"Thread 2");
if (result2 != 0) {
std::cerr << "Error: pthread_create failed for 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 << " started" << std::endl;
// 在這里執行你的線程任務
std::cout << thread_name << " finished" << std::endl;
pthread_exit(NULL);
}
g++ -o multithread_example multithread_example.cpp -pthread
注意:-pthread
選項告訴編譯器鏈接pthread庫。
./multithread_example
這個示例創建了兩個線程,它們并發地執行thread_function
函數。pthread_create
函數用于創建線程,pthread_join
函數用于等待線程結束。