在Linux環境下,C++可以通過多種方式實現并發編程。以下是一些常用的方法:
<thread>
庫可以輕松地創建和管理線程。#include <iostream>
#include <thread>
void helloFunction() {
std::cout << "Hello from a thread!" << std::endl;
}
int main() {
std::thread t(helloFunction);
t.join(); // 等待線程完成
return 0;
}
#include <iostream>
#include <thread>
#include <mutex>
std::mutex mtx; // 創建一個互斥鎖
void printMessage(const std::string& msg) {
mtx.lock(); // 加鎖
std::cout << msg << std::endl;
mtx.unlock(); // 解鎖
}
int main() {
std::thread t1(printMessage, "Hello from thread 1");
std::thread t2(printMessage, "Hello from thread 2");
t1.join();
t2.join();
return 0;
}
#include <iostream>
#include <thread>
#include <mutex>
#include <condition_variable>
std::mutex mtx;
std::condition_variable cv;
bool ready = false;
void printId(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];
// spawn 10 threads:
for (int i = 0; i < 10; ++i)
threads[i] = std::thread(printId, i);
std::cout << "10 threads ready to race..." << std::endl;
go(); // go!
for (auto &th : threads) th.join();
return 0;
}
<atomic>
庫提供的原子類型和操作,可以在不使用鎖的情況下實現線程安全的操作。#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: " << counter << std::endl;
return 0;
}
信號量(Semaphores):雖然C++標準庫沒有直接提供信號量,但可以使用POSIX信號量或者Boost庫中的信號量。
管道(Pipes)和命名管道(Named Pipes):用于線程間或進程間的通信。
消息隊列(Message Queues):同樣用于線程間或進程間的通信,可以使用POSIX消息隊列或者System V消息隊列。
共享內存(Shared Memory):允許多個進程訪問同一塊內存區域,可以使用POSIX共享內存或者System V共享內存。
遠程過程調用(RPC):如gRPC,允許一個程序調用另一個地址空間(通常是另一臺機器上)的過程或函數。
異步編程模型(Asynchronous Programming Model):使用<future>
和<async>
庫來執行異步操作。
#include <iostream>
#include <future>
int asyncAdd(int x, int y) {
return x + y;
}
int main() {
// 返回一個future對象,它將持有異步操作的結果
std::future<int> result = std::async(std::launch::async, asyncAdd, 5, 7);
// 可以繼續做其他事情
std::cout << "Waiting for the result..." << std::endl;
// 獲取異步操作的結果
std::cout << "The result is " << result.get() << std::endl;
return 0;
}
選擇哪種并發模型取決于具體的應用場景和需求。例如,如果需要簡單的線程管理,<thread>
庫可能是最直接的選項。如果需要更復雜的同步控制,可能需要使用互斥鎖、條件變量或原子操作。對于高性能的并發處理,可能需要考慮無鎖數據結構和算法。