在Ubuntu上進行C++并發編程,你可以使用多種方法和技術。以下是一些常見的并發編程方法:
C++11線程庫:
C++11引入了標準線程庫,它提供了std::thread
類來創建和管理線程。這是一個跨平臺的解決方案,可以在Ubuntu上使用。
#include <iostream>
#include <thread>
void helloFunction() {
std::cout << "Hello from a thread!" << std::endl;
}
int main() {
std::thread t(helloFunction);
t.join(); // 等待線程完成
return 0;
}
互斥鎖:
當多個線程需要訪問共享資源時,可以使用std::mutex
來保護這些資源。
#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;
}
條件變量:
std::condition_variable
可以用來同步線程,使得線程可以在某個條件滿足時才繼續執行。
#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;
}
原子操作:
std::atomic
提供了原子操作,可以在多線程環境中安全地進行某些操作,而不需要顯式的鎖。
#include <iostream>
#include <thread>
#include <atomic>
std::atomic<int> sharedValue(0);
void incrementValue() {
++sharedValue; // 原子操作
}
int main() {
std::thread t1(incrementValue);
std::thread t2(incrementValue);
t1.join();
t2.join();
std::cout << "Shared value: " << sharedValue << std::endl;
return 0;
}
異步任務:
C++11還提供了std::async
和std::future
來執行異步任務,并獲取它們的結果。
#include <iostream>
#include <future>
int compute(int x) {
return x * x;
}
int main() {
std::future<int> result = std::async(std::launch::async, compute, 42);
std::cout << "The answer is " << result.get() << std::endl; // 獲取異步任務的結果
return 0;
}
線程池: 雖然C++標準庫沒有直接提供線程池的實現,但你可以使用第三方庫,如Boost.Asio或者自己實現一個簡單的線程池。
在Ubuntu上編譯C++并發程序時,確保使用支持C++11或更高標準的編譯器選項,例如:
g++ -std=c++11 -pthread your_program.cpp -o your_program
-pthread
選項告訴編譯器鏈接線程支持庫,并啟用相關的預處理器定義。