在Linux環境下使用C++進行并發編程,主要有以下幾種方式:
POSIX Threads 是一種標準的線程庫,適用于大多數Unix-like系統,包括Linux。
包含頭文件:
#include <pthread.h>
定義線程函數:
void* thread_function(void* arg) {
// 線程執行的代碼
return NULL;
}
創建線程:
pthread_t thread_id;
int result = pthread_create(&thread_id, NULL, thread_function, NULL);
if (result != 0) {
// 處理錯誤
}
等待線程結束:
pthread_join(thread_id, NULL);
銷毀線程(可選):
pthread_exit(NULL);
#include <iostream>
#include <pthread.h>
void* thread_function(void* arg) {
std::cout << "Thread is running" << std::endl;
return NULL;
}
int main() {
pthread_t thread_id;
int result = pthread_create(&thread_id, NULL, thread_function, NULL);
if (result != 0) {
std::cerr << "Error creating thread" << std::endl;
return 1;
}
pthread_join(thread_id, NULL);
std::cout << "Thread finished" << std::endl;
return 0;
}
C++11 引入了標準庫線程支持,提供了更現代和安全的接口。
包含頭文件:
#include <thread>
定義線程函數:
void thread_function() {
// 線程執行的代碼
}
創建線程:
std::thread t(thread_function);
等待線程結束:
t.join();
分離線程(可選):
t.detach();
#include <iostream>
#include <thread>
void thread_function() {
std::cout << "Thread is running" << std::endl;
}
int main() {
std::thread t(thread_function);
t.join();
std::cout << "Thread finished" << std::endl;
return 0;
}
std::async 提供了一種更高級的方式來執行異步任務,它會自動管理線程的創建和銷毀。
包含頭文件:
#include <future>
定義任務函數:
int task_function() {
// 任務執行的代碼
return 42;
}
啟動異步任務:
std::future<int> result = std::async(std::launch::async, task_function);
獲取任務結果:
int value = result.get();
#include <iostream>
#include <future>
int task_function() {
std::cout << "Task is running" << std::endl;
return 42;
}
int main() {
std::future<int> result = std::async(std::launch::async, task_function);
std::cout << "Waiting for task to finish..." << std::endl;
int value = result.get();
std::cout << "Task finished with result: " << value << std::endl;
return 0;
}
C++11 及其后續版本還提供了一些并發容器和算法,如 std::atomic、std::mutex、std::lock_guard、std::unique_lock 等,用于實現線程安全的操作。
#include <iostream>
#include <thread>
#include <mutex>
std::mutex mtx;
void print_block(int n, char c) {
std::lock_guard<std::mutex> guard(mtx);
for (int i = 0; i < n; ++i) {
std::cout << c;
}
std::cout << '\n';
}
int main() {
std::thread th1(print_block, 50, '*');
std::thread th2(print_block, 50, '$');
th1.join();
th2.join();
return 0;
}
通過這些方法,你可以在Linux環境下使用C++進行高效的并發編程。選擇哪種方法取決于你的具體需求和應用場景。