在Linux環境下使用C++進行并發編程,主要有以下幾種方式:
POSIX Threads(簡稱pthreads)是C語言的一個標準線程庫,也可以在C++中使用。
#include <pthread.h>
void*
,參數為void*
。pthread_create
函數。pthread_join
函數。pthread_exit
函數。#include <iostream>
#include <pthread.h>
void* threadFunction(void* arg) {
std::cout << "Thread is running" << std::endl;
pthread_exit(nullptr);
}
int main() {
pthread_t thread;
int result = pthread_create(&thread, nullptr, threadFunction, nullptr);
if (result != 0) {
std::cerr << "Error creating thread" << std::endl;
return 1;
}
void* status;
pthread_join(thread, &status);
std::cout << "Thread has finished" << std::endl;
return 0;
}
C++11引入了標準庫線程支持,提供了更現代和類型安全的線程管理。
#include <thread>
std::thread
對象。join
或detach
方法。#include <iostream>
#include <thread>
void threadFunction() {
std::cout << "Thread is running" << std::endl;
}
int main() {
std::thread t(threadFunction);
t.join(); // 等待線程結束
std::cout << "Thread has finished" << std::endl;
return 0;
}
std::async
)std::async
是C++11引入的另一種并發編程方式,它返回一個std::future
對象,可以用來獲取異步任務的結果。
#include <iostream>
#include <future>
int asyncFunction() {
std::this_thread::sleep_for(std::chrono::seconds(2));
return 42;
}
int main() {
std::future<int> result = std::async(std::launch::async, asyncFunction);
std::cout << "Waiting for the result..." << std::endl;
int value = result.get(); // 獲取結果
std::cout << "Result is: " << value << std::endl;
return 0;
}
C++標準庫提供了一些并發容器和算法,如std::atomic
、std::mutex
、std::lock_guard
等,用于實現線程安全的操作。
#include <iostream>
#include <thread>
#include <atomic>
std::atomic<int> counter(0);
void incrementCounter() {
for (int i = 0; i < 100000; ++i) {
counter++;
}
}
int main() {
std::thread t1(incrementCounter);
std::thread t2(incrementCounter);
t1.join();
t2.join();
std::cout << "Counter value: " << counter << std::endl;
return 0;
}
std::async
:適用于需要異步任務和結果獲取的場景。選擇哪種方式取決于具體的需求和應用場景。