在Linux環境下,C++并發編程模型主要依賴于POSIX線程庫(pthread)和C++11引入的線程庫。以下是一些常見的并發編程模型:
POSIX Threads是一個跨平臺的線程庫,提供了創建和管理線程的API。
#include <pthread.h>
#include <iostream>
pthread_mutex_t mutex;
int shared_resource = 0;
void* thread_func(void* arg) {
pthread_mutex_lock(&mutex);
shared_resource++;
std::cout << "Thread ID: " << pthread_self() << ", Shared Resource: " << shared_resource << std::endl;
pthread_mutex_unlock(&mutex);
return nullptr;
}
int main() {
pthread_t thread1, thread2;
pthread_mutex_init(&mutex, nullptr);
pthread_create(&thread1, nullptr, thread_func, nullptr);
pthread_create(&thread2, nullptr, thread_func, nullptr);
pthread_join(thread1, nullptr);
pthread_join(thread2, nullptr);
pthread_mutex_destroy(&mutex);
return 0;
}
C++11引入了標準庫中的線程支持,提供了更現代和易用的接口。
#include <iostream>
#include <thread>
#include <mutex>
#include <condition_variable>
std::mutex mtx;
std::condition_variable cv;
bool ready = false;
void print_id(int id) {
std::unique_lock<std::mutex> lck(mtx);
cv.wait(lck, []{return ready;});
std::cout << "Thread " << id << std::endl;
}
void go() {
std::lock_guard<std::mutex> lck(mtx);
ready = true;
cv.notify_all();
}
int main() {
std::thread threads[10];
for (int i = 0; i < 10; ++i) {
threads[i] = std::thread(print_id, i);
}
std::this_thread::sleep_for(std::chrono::seconds(1));
go();
for (auto& th : threads) {
th.join();
}
return 0;
}
C++11引入了std::async
和std::future
,提供了更高級的異步編程模型。
#include <iostream>
#include <future>
int add(int x, int y) {
return x + y;
}
int main() {
std::future<int> result = std::async(std::launch::async, add, 3, 4);
std::cout << "Waiting for result..." << std::endl;
std::cout << "Result: " << result.get() << std::endl;
return 0;
}
C++標準庫提供了一些并發安全的容器和算法,例如std::atomic
、std::shared_mutex
等。
#include <iostream>
#include <thread>
#include <vector>
#include <atomic>
std::atomic<int> atomic_counter(0);
void increment_counter(int iterations) {
for (int i = 0; i < iterations; ++i) {
atomic_counter++;
}
}
int main() {
std::vector<std::thread> threads;
int iterations = 100000;
for (int i = 0; i < 10; ++i) {
threads.emplace_back(increment_counter, iterations);
}
for (auto& th : threads) {
th.join();
}
std::cout << "Final Counter Value: " << atomic_counter.load() << std::endl;
return 0;
}
這些模型和工具可以幫助你在Linux環境下進行高效的C++并發編程。選擇合適的模型取決于你的具體需求和應用場景。