在Ubuntu中,C++程序可以通过多种方式处理并发问题。以下是一些常用的方法:
C++11引入了标准库中的线程支持,可以通过<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];
for (int i = 0; i < 10; ++i) {
threads[i] = std::thread(printId, i);
}
std::this_thread::sleep_for(std::chrono::seconds(1)); // 等待一段时间
go(); // 通知线程开始执行
for (auto& th : threads) {
th.join();
}
return 0;
}
原子操作可以在不使用锁的情况下保证操作的原子性。
#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;
}
信号量是一种更高级的同步机制,可以用来控制对共享资源的访问。
#include <iostream>
#include <thread>
#include <semaphore>
std::binary_semaphore sem(1); // 二进制信号量
void printMessage(const std::string& msg) {
sem.acquire(); // 获取信号量
std::cout << msg << std::endl;
sem.release(); // 释放信号量
}
int main() {
std::thread t1(printMessage, "Hello from thread 1");
std::thread t2(printMessage, "Hello from thread 2");
t1.join();
t2.join();
return 0;
}
在Ubuntu中处理C++程序的并发问题时,可以使用标准库提供的线程支持、互斥锁、条件变量、原子操作和信号量等工具。选择合适的同步机制取决于具体的应用场景和需求。