浅谈C++之多线程实现

server/2024/10/19 12:50:22/

一、基本介绍

        传统的C++(C++11之前)中并没有引入线程这个概念,在C++11出来之前,如果我们想要在C++中实现多线程,需要借助操作系统平台提供的API,比如Linux的<pthread.h>,或者windows下的<windows.h> 。

        C++11提供了语言层面上的多线程,包含在头文件<thread>中。它解决了跨平台的问题,提供了管理线程、保护共享数据、线程间同步操作、原子操作等类

二、实现方式

C++11标准库中的<thread>

C++11引入了对多线程的原生支持,可以通过std::thread类来创建和管理线程。

#include <thread>
#include <iostream>void hello() {std::cout << "Hello from thread" << std::endl;
}int main() {std::thread t(hello);t.join();return 0;
}

C++11标准库中的<future>

std::futurestd::async可以用来异步地获取线程的执行结果。

#include <future>
#include <iostream>int compute() {return 42;
}int main() {std::future<int> result = std::async(std::launch::async, compute);std::cout << "The result is " << result.get() << std::endl;return 0;
}

C++11标准库中的<mutex>

用于线程同步,包括互斥锁(std::mutex)、递归锁(std::recursive_mutex)、时间锁(std::timed_mutex)、共享锁(std::shared_mutex)等。

#include <mutex>
#include <iostream>std::mutex mtx;
int counter = 0;void increment() {std::lock_guard<std::mutex> lock(mtx);++counter;
}int main() {std::thread t1(increment);std::thread t2(increment);t1.join();t2.join();std::cout << "Counter: " << counter << std::endl;return 0;
}

C++11标准库中的<condition_variable>

用于线程间的同步,允许一个或多个线程等待特定条件的发生。

#include <iostream>
#include <mutex>
#include <condition_variable>std::mutex mtx;
std::condition_variable cv;
bool ready = false;void print_id(int id) {std::unique_lock<std::mutex> lock(mtx);while (!ready) { cv.wait(lock); }std::cout << "Thread " << id << '\n';
}void go() {std::unique_lock<std::mutex> lock(mtx);ready = true;cv.notify_all();
}int main() {std::thread threads[10];// 启动10个线程for (int i = 0; i < 10; ++i)threads[i] = std::thread(print_id, i);std::cout << "10 threads ready to race...\n";go(); // 准备开始for (auto& th : threads) th.join();
}

C++20中的协程

C++20引入了协程,提供了一种更高级的异步编程模型。

#include <iostream>
#include <coroutine>
#include <thread>generator<int> GetNumbers() {for (int i = 0; i < 5; ++i) {std::this_thread::sleep_for(std::chrono::seconds(1));co_yield i;}
}int main() {for (auto n : GetNumbers()) {std::cout << n << std::endl;}return 0;
}

使用第三方库

如Boost库中的线程库(boost::thread),提供了在C++11之前实现多线程的方法。

#include <boost/thread.hpp>
#include <iostream>void hello() {std::cout << "Hello from Boost thread" << std::endl;
}int main() {boost::thread t(hello);t.join();return 0;
}

操作系统级别的线程库

如Windows的WinAPI中的线程函数(CreateThread)或POSIX线程(pthreads)。

// POSIX threads example
#include <pthread.h>
#include <iostream>void* hello(void* arg) {std::cout << "Hello from POSIX thread" << std::endl;return NULL;
}int main() {pthread_t thread;pthread_create(&thread, NULL, hello, NULL);pthread_join(thread, NULL);return 0;
}


http://www.ppmy.cn/server/123075.html

相关文章

搜维尔科技:测试Xsens功能,通过空中移动在弹簧地板上进行捕捉

测试Xsens功能&#xff0c;通过空中移动在弹簧地板上进行捕捉 搜维尔科技&#xff1a;测试Xsens功能&#xff0c;通过空中移动在弹簧般的地板上进行动作捕捉

Elasticsearch详细笔记(三):ES客户端--RestClient操作索引库、文档

目录 1.RestAPI 1.1.初始化RestClient 1.2.创建索引库 1.2.1.Mapping映射 1.2.2.创建索引 1.3.删除索引库 1.4.查询索引库 1.5.总结 2.RestClient操作文档 2.1.新增文档 2.1.1.实体类 2.1.2.API语法 2.1.3.完整代码 2.2.查询文档 2.2.1.语法说明 2.2.2.完整代码…

基于SpringBoot+Vue的小儿推拿培训管理系统

作者&#xff1a;计算机学姐 开发技术&#xff1a;SpringBoot、SSM、Vue、MySQL、JSP、ElementUI、Python、小程序等&#xff0c;“文末源码”。 专栏推荐&#xff1a;前后端分离项目源码、SpringBoot项目源码、Vue项目源码、SSM项目源码 精品专栏&#xff1a;Java精选实战项目…

WPF入门教学十九 属性动画与时间线

在WPF中&#xff0c;属性动画是通过改变对象的依赖属性值来创建动画效果的一种方式。时间线&#xff08;Timeline&#xff09;是控制动画播放进度的核心组件。WPF提供了多种类型的动画和时间线&#xff0c;包括DoubleAnimation、ColorAnimation、PointAnimation等&#xff0c;以…

【手机直连卫星】除了华为Mate 60 Pro,支持卫星通信的手机还有哪些款

2023年底&#xff0c;华为推出的Mate 60 Pro手机&#xff0c;开创了智能手机卫星通信的新纪元。它支持卫星电话通话和短信功能&#xff0c;让用户即使在偏远山野或深海之上也能保持与外界的联系。这一技术的加入&#xff0c;无疑为户外探险者和遥远地区的工作者提供了难以估量的…

24.9.27学习笔记

Xavier初始化&#xff0c;也称为Glorot初始化&#xff0c;是一种在训练深度神经网络时用于初始化网络权重的策略。它的核心思想是在网络的每一层保持前向传播和反向传播时的激活值和梯度的方差尽可能一致&#xff0c;以避免梯度消失或梯度爆炸的问题。这种方法特别适用于激活函…

506. 相对名次 哈希表

506. 相对名次 难度指数&#xff1a;5 简单 相关标签 相关企业 给你一个长度为 n 的整数数组 score &#xff0c;其中 score[i] 是第 i 位运动员在比赛中的得分。所有得分都 互不相同 。 运动员将根据得分 决定名次 &#xff0c;其中名次第 1 的运动员得分最高&#xff0…

[Linux]ubuntu安装nvidia显卡驱动登录后黑屏

一、问题描述 在tty&#xff08;按下ctrlaltF1或者F2或者F3&#xff09;或者ssh等无界面下安装完成nvidia驱动&#xff0c;可以使用nvidia-smi查看驱动信息&#xff0c;并且重启开机后可以显示登录界面&#xff0c;但是输入登录密码后黑屏。 二、可能的原因及解决方案 1. 可…