浅谈C++之线程管理

一、基本介绍

C++11 提供了强大的多线程支持,涵盖了线程的创建、同步、共享数据管理等,极大简化了多线程编程的复杂性。

  • 线程:一个程序执行流的最小单位。每个线程都有自己的程序计数器、栈、寄存器等。
  • 多线程:程序可以同时执行多个任务,提高了程序的并发能力。
  • 并行与并发:并行是多个线程在多个处理器上同时运行;并发是多个线程在同一处理器上通过时间片轮转方式运行。

二、关键概念和示例

1. 包含头文件

首先,你需要包含头文件<thread>来使用线程库。

cpp 复制代码
#include <thread>

2. 创建线程

使用std::thread类来创建线程。你可以将一个函数或对象作为参数传递给std::thread的构造函数,这个函数或对象将在新线程中执行。

cpp 复制代码
#include <iostream>
#include <thread>

void hello() {
    std::cout << "Hello from a thread!" << std::endl;
}

int main() {
    std::thread t(hello);
    t.join();  // 等待线程t完成
    return 0;
}

3. 传递参数给线程

你可以将参数传递给线程函数。

cpp 复制代码
#include <iostream>
#include <thread>

void print_message(const std::string& message) {
    std::cout << message << std::endl;
}

int main() {
    std::string message = "Hello from another thread!";
    std::thread t(print_message, message);
    t.join();
    return 0;
}

4. 线程的生命周期

  • join(): 阻塞调用线程,直到被join的线程完成执行。
  • detach(): 允许线程独立执行。主线程可以继续执行,而不需要等待子线程完成。
cpp 复制代码
std::thread t(hello);
t.detach();  // 线程t现在独立执行

5. 线程同步

使用互斥锁(std::mutex)和条件变量(std::condition_variable)来同步线程。

cpp 复制代码
#include <iostream>
#include <thread>
#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];
    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();
    return 0;
}

6. 线程局部存储

使用thread_local关键字定义线程局部存储,每个线程都有自己的变量副本。

cpp 复制代码
#include <iostream>
#include <thread>

thread_local int x = 0;

void increment() {
    x = x + 1;
    std::cout << "Thread " << std::this_thread::get_id() << " x = " << x << std::endl;
}

int main() {
    std::thread t1(increment);
    std::thread t2(increment);
    t1.join();
    t2.join();
    return 0;
}

7. 原子操作

使用std::atomic来处理简单的同步需求。

cpp 复制代码
#include <iostream>
#include <thread>
#include <atomic>

std::atomic<int> count(0);

void add() {
    for (int i = 0; i < 10000; ++i) {
        count += 1;
    }
}

int main() {
    std::thread t1(add);
    std::thread t2(add);
    t1.join();
    t2.join();
    std::cout << "Count: " << count << std::endl;
    return 0;
}
相关推荐
小凡子空白在线学习几秒前
8 非静态数据成员默认初始化
开发语言·前端·javascript
大母猴啃编程7 分钟前
C++基础---类和对象(上)
c语言·开发语言·数据结构·c++·学习·算法·青少年编程
倩倩_ICE_王王8 分钟前
PHP安装后Apache无法运行的问题
开发语言·php·apache·httpd.conf
Amo Xiang31 分钟前
2024 Python3.10 系统入门+进阶(十六):正则表达式
开发语言·python·正则表达式
翔云API31 分钟前
APP集成人脸识别接口-C#人脸识别API接口
开发语言·c#
Hundred billion40 分钟前
【牛客刷题记录】【JAVA】二分查找
java·开发语言
JovaZou44 分钟前
[Python学习日记-35] Python 中的内置函数(上)
开发语言·python·学习
鸽芷咕1 小时前
【Python报错已解决】KeyError: ‘key‘
开发语言·python
懒洋洋大魔王1 小时前
Java面向对象第三章封装与继承练习题
java·开发语言
大神薯条老师1 小时前
Python从入门到高手4.1节-掌握条件控制语句
开发语言·python·算法·机器学习·数据分析