阅读量:0
在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;
}
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;
{
std::lock_guard lck(mtx) ;
ready = true;
}
cv.notify_all(); // 通知所有等待的线程
for (auto &th : threads) th.join();
return 0;
}
- 原子操作:使用
库来进行无锁编程。
#include
#include
#include
std::atomic<int> sharedValue(0);
void incrementValue() {
for (int i = 0; i < 1000; ++i) {
sharedValue++; // 原子操作
}
}
int main() {
std::thread t1(incrementValue);
std::thread t2(incrementValue);
t1.join();
t2.join();
std::cout << "Final value of sharedValue: " << sharedValue << std::endl;
return 0;
}
- 异步编程:使用
和库来执行异步操作。
#include
#include
int compute(int x) {
return x * x;
}
int main() {
// 返回一个future对象,它将持有异步计算的结果
std::future<int> result = std::async(std::launch::async, compute, 4);
// 可以继续做其他事情
std::cout << "Waiting for result..." << std::endl;
// 获取异步操作的结果
std::cout << "Result: " << result.get() << std::endl;
return 0;
}
-
信号量:虽然C++标准库没有直接提供信号量的实现,但可以使用POSIX信号量(
semaphore.h)或者自己封装一个。 -
管道和命名管道:使用
、等来进行进程间通信。 -
消息队列:使用POSIX消息队列(
mqueue.h)或者System V消息队列来进行进程间通信。 -
共享内存:使用POSIX共享内存(
shm_open.h)或者System V共享内存来进行进程间通信。 -
套接字:使用
等来进行网络编程,实现跨机器的并发。
选择合适的并发模型取决于具体的应用场景和需求。在实际编程中,可能需要结合使用多种技术来实现高效且健壮的并发程序。
以上就是关于“Linux C++编程中如何进行并发编程”的相关介绍,筋斗云是国内较早的云主机应用的服务商,拥有10余年行业经验,提供丰富的云服务器、租用服务器等相关产品服务。云服务器资源弹性伸缩,主机vCPU、内存性能强悍、超高I/O速度、故障秒级恢复;电子化备案,提交快速,专业团队7×24小时服务支持!
简单好用、高性价比云服务器租用链接:https://www.jindouyun.cn/product/cvm