在Ubuntu下使用C++實現并發與同步控制,通常會用到C++11標準庫中的<thread>、<mutex>、<condition_variable>等組件。以下是一些基本的實現方法:
std::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;
}
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::lock_guard簡化鎖的管理#include <iostream>
#include <thread>
#include <mutex>
std::mutex mtx;
void printMessage(const std::string& msg) {
std::lock_guard<std::mutex> lock(mtx); // 自動管理鎖
std::cout << msg << std::endl;
}
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> 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;
}
這些是C++中實現并發與同步控制的一些基本方法。在實際應用中,可能需要根據具體情況選擇合適的同步機制,并注意避免死鎖和其他并發問題。