当前位置: 首页 > article >正文

浅谈C++之多线程实现

一、基本介绍

        传统的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.kler.cn/news/318670.html

相关文章:

  • 口语训练材料
  • 力扣【283-移动零】【数组-C语言】
  • 微服务之服务保护
  • git checkout -b dev origin/dev
  • golang cmd.exec 执行命令后报错 No such file or directory
  • 最优化理论与自动驾驶(二-补充):求解算法(梯度下降法、牛顿法、高斯牛顿法以及LM法,C++代码)
  • Java-数据结构-排序(三) |ू・ω・` )
  • 【网络安全】密码学的新进展
  • Nginx 如何开启压缩
  • 伊犁云计算22-1 rhel8 dhcp 配置
  • YOLOv10改进,YOLOv10主干网络替换为VanillaNet( CVPR 2023 华为提出的全新轻量化架构),大幅度涨点
  • 操作系统知识3
  • 华为全联接大会HUAWEI Connect 2024印象(一):OpenEuler
  • uniapp沉浸式导航栏+自定义导航栏组件
  • 深入理解端口、端口号及FTP的基本工作原理
  • CREO教程——2 绘制标准图纸
  • python/requests库的使用/爬虫基础工具/
  • 最新版C/C++通过CLion2024进行Linux远程开发保姆级教学
  • 【Docker】基于docker compose部署artifactory-cpp-ce服务
  • 【车联网安全】车端知识调研
  • 产品经理面试整理-软件产品经理的常用工具
  • SpringBoot框架在文档管理中的创新应用
  • 系统架构笔记-3-信息系统基础知识
  • 探讨MySQL中的GROUP BY语句大小写敏感性
  • SegFormer网络结构的学习和重构
  • CSP-S 2024 提高级 第一轮(初赛) 阅读程序(2)
  • 【OSS安全最佳实践】降低因操作失误等原因导致数据丢失的风险
  • 【C++笔试强训】如何成为算法糕手Day2
  • 【c++】知识点
  • 分布式光伏监控系统 在鄂尔多斯市鄂托克旗某煤矿项目中的应用