在Linux环境下使用C++进行并发编程,可以采用多种方法。以下是一些常用的并发编程技术:
- 多线程:使用C++11引入的
库可以轻松地创建和管理线程。
#include#include void helloFunction() { std::cout << "Hello from a thread!" << std::endl; } int main() { std::thread t(helloFunction); t.join(); // 等待线程完成 return 0; }
- 互斥锁:使用
库来保护共享资源,防止数据竞争。
#include
#include
#include
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
#include
#include
#include
std::mutex mtx;
std::condition_variable cv;
bool ready = false;
void printId(int id) {
std::unique_lock lck(mtx);
cv.wait(lck, []{return ready;}); // 等待条件变量
std::cout << "Thread " << id << std::endl;
}
void go() {
std::lock_guard 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;
}
- 原子操作:使用
库来进行原子操作,保证操作的原子性。
#include
#include
#include
std::atomic counter(0);
void incrementCounter() {
for (int i = 0; i < 1000; ++i) {
counter.fetch_add(1); // 原子加法
}
}
int main() {
std::thread t1(incrementCounter);
std::thread t2(incrementCounter);
t1.join();
t2.join();
std::cout << "Counter: " << counter.load() << std::endl; // 输出计数器的值
return 0;
}
- 异步编程:使用
和
来进行异步编程。
#include
#include
int compute(int x) {
return x * x;
}
int main() {
std::promise prms;
std::future ftr = prms.get_future();
std::thread t(compute, 5, std::move(prms)); // 将promise传递给线程
std::cout << "Waiting for result..." << std::endl;
std::cout << "Result: " << ftr.get() << std::endl; // 获取结果
t.join();
return 0;
}
-
信号量:虽然C++标准库没有直接提供信号量的实现,但可以使用POSIX信号量(
semaphore.h
)或者自己封装一个。 -
管道和命名管道:使用
、
、
等系统调用来创建和使用管道进行进程间通信。 -
消息队列:使用
系统调用来创建和使用消息队列进行进程间通信。 -
共享内存:使用
、
等系统调用来创建和使用共享内存。 -
套接字:使用
、
等系统调用来进行网络编程和进程间通信。
这些是Linux环境下C++并发编程的一些基本方法。在实际应用中,可能需要结合多种技术来实现复杂的并发控制。此外,还可以使用第三方库,如Boost.Asio、Qt Concurrent等,来简化并发编程。