浅谈C++之多线程实现

一、基本介绍

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

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

二、实现方式

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

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

cpp 复制代码
#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可以用来异步地获取线程的执行结果。

cpp 复制代码
#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)等。

cpp 复制代码
#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>

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

cpp 复制代码
#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引入了协程,提供了一种更高级的异步编程模型。

cpp 复制代码
#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之前实现多线程的方法。

cpp 复制代码
#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)。

cpp 复制代码
// 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;
}
相关推荐
雪的期许9 分钟前
go结构体默认值和校验器(go-defaults、go-validator)
开发语言·后端·golang
心外无物的工作技术笔记10 分钟前
【Go语言基础——一个Go语言项目典型的文件结构示例】
开发语言·笔记·golang·go
小学徒WQ15 分钟前
Java ReentrantLock
java·开发语言
小黑0315 分钟前
Scala第一天
开发语言·scala
灰_灰丶灰23 分钟前
【并发】ThreadLocal 为什么会内存泄露
java·开发语言·jvm
阿华的代码王国26 分钟前
【JavaEE】——CAS指令和ABA问题
java·开发语言
会编程的果子君32 分钟前
C++系列-继承
开发语言·c++·算法
打工小熊猫1 小时前
如何在CMakeList项目中集成GNU Autotools 构建模块
c++·gnu
friklogff1 小时前
【C#生态园】构建高效PDF应用:全面解析C#六大PDF生成库
开发语言·pdf·c#
Qiuner1 小时前
虚拟机三种网络模式详解
开发语言·网络·php