在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;
}
<future>
和<async>
库可以执行异步任务,并且可以获取它们的结果。#include <iostream>
#include <future>
int add(int x, int y) {
return x + y;
}
int main() {
std::async(std::launch::async, add, 5, 7); // 异步执行add函数
// 可以继续执行其他操作
// ...
std::future<int> result = std::async(std::launch::async, add, 5, 7).get(); // 获取结果
std::cout << "The result is " << result << std::endl;
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...\n";
go(); // go!
for (auto &th : threads) th.join();
return 0;
}
信号量:虽然C++标准库没有直接提供信号量的实现,但是可以使用POSIX信号量(semaphore.h
)或者Boost库中的信号量。
管道和命名管道:使用<sys/types.h>
、<sys/stat.h>
、<fcntl.h>
、<unistd.h>
等系统头文件可以实现进程间通信(IPC),包括管道和命名管道。
消息队列:同样使用系统头文件,可以实现消息队列来进行进程间通信。
共享内存:使用<sys/ipc.h>
、<sys/shm.h>
等系统头文件可以实现共享内存,允许多个进程访问同一块内存区域。
套接字:使用<sys/socket.h>
、<netinet/in.h>
、<arpa/inet.h>
等系统头文件可以实现网络编程,包括TCP和UDP套接字。
选择哪种并发模型取决于具体的应用场景和需求。多线程和异步任务通常用于提高程序的执行效率,而互斥锁、条件变量等同步机制则用于保证线程安全。