在Linux环境下,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;
}
#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;
}
<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;
}
信号量(Semaphores):虽然C++标准库没有直接提供信号量,但可以使用POSIX信号量或者Boost库中的信号量。
管道(Pipes)和命名管道(Named Pipes):用于线程间或进程间的通信。
消息队列(Message Queues):同样用于线程间或进程间的通信,可以使用POSIX消息队列或者System V消息队列。
共享内存(Shared Memory):允许多个进程访问同一块内存区域,可以使用POSIX共享内存或者System V共享内存。
远程过程调用(RPC):如gRPC,允许一个程序调用另一个地址空间(通常是另一台机器上)的过程或函数。
异步编程模型(Asynchronous Programming Model):使用<future>
和<async>
库来执行异步操作。
#include <iostream>
#include <future>
int asyncAdd(int x, int y) {
return x + y;
}
int main() {
// 返回一个future对象,它将持有异步操作的结果
std::future<int> result = std::async(std::launch::async, asyncAdd, 5, 7);
// 可以继续做其他事情
std::cout << "Waiting for the result..." << std::endl;
// 获取异步操作的结果
std::cout << "The result is " << result.get() << std::endl;
return 0;
}
选择哪种并发模型取决于具体的应用场景和需求。例如,如果需要简单的线程管理,<thread>
库可能是最直接的选项。如果需要更复杂的同步控制,可能需要使用互斥锁、条件变量或原子操作。对于高性能的并发处理,可能需要考虑无锁数据结构和算法。