在Ubuntu上使用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;
}
<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;
}
<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;
}
<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;
}
<future>和<async>来执行异步操作。#include <iostream>
#include <future>
int asyncFunction() {
std::this_thread::sleep_for(std::chrono::seconds(1)); // 模拟耗时操作
return 42;
}
int main() {
std::future<int> result = std::async(std::launch::async, asyncFunction);
std::cout << "Waiting for the result..." << std::endl;
int value = result.get(); // 获取异步操作的结果
std::cout << "Result: " << value << std::endl;
return 0;
}
<semaphore.h>)来进行线程同步。#include <iostream>
#include <thread>
#include <semaphore.h>
sem_t sem;
void worker() {
sem_wait(&sem); // 等待信号量
std::cout << "Worker thread is running" << std::endl;
sem_post(&sem); // 发送信号量
}
int main() {
sem_init(&sem, 0, 0); // 初始化信号量,初始值为0
std::thread t(worker);
std::cout << "Main thread is doing some work..." << std::endl;
std::this_thread::sleep_for(std::chrono::seconds(1)); // 模拟工作
sem_post(&sem); // 发送信号量,允许工作线程运行
t.join();
sem_destroy(&sem); // 销毁信号量
return 0;
}
在使用这些并发编程技术时,请确保你理解了它们的工作原理以及可能出现的竞态条件和死锁等问题。正确地使用同步机制对于编写高效且安全的并发程序至关重要。