在Ubuntu上进行C++开发时,实现并发控制可以通过多种方式,包括使用线程、互斥锁、条件变量、信号量等。以下是一些基本的并发控制方法:
#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;
}
在C++中没有直接的信号量实现,但可以使用POSIX信号量或者通过互斥锁和条件变量来模拟。
#include <atomic>
#include <iostream>
#include <thread>
std::atomic<int> sharedValue(0);
void incrementValue() {
for (int i = 0; i < 1000; ++i) {
sharedValue.fetch_add(1); // 原子加法
}
}
int main() {
std::thread t1(incrementValue);
std::thread t2(incrementValue);
t1.join();
t2.join();
std::cout << "Final value of sharedValue: " << sharedValue.load() << std::endl;
return 0;
}
在实现并发控制时,需要注意避免死锁、竞态条件等问题。合理使用同步机制,确保线程安全。此外,还可以考虑使用高级并发库,如Boost.Asio,它提供了更高级别的网络和低级I/O编程接口,以及并发控制功能。