浅谈C++之线程管理

news/2024/9/29 13:56:27/

一、基本介绍

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

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

二、关键概念和示例

1. 包含头文件

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

#include <thread>

2. 创建线程

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

#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. 传递参数给线程

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

#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(): 允许线程独立执行。主线程可以继续执行,而不需要等待子线程完成。

std::thread t(hello);
t.detach();  // 线程t现在独立执行

5. 线程同步

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

#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关键字定义线程局部存储,每个线程都有自己的变量副本。

#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来处理简单的同步需求。

#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;
}


http://www.ppmy.cn/news/1531942.html

相关文章

JIT(Just-In-Time)

JIT&#xff08;Just-In-Time&#xff09;即时编译是一种在程序运行时动态编译字节码为机器码的技术&#xff0c;常用于提高代码执行效率。它结合了解释型语言的灵活性与编译型语言的高效性。 JIT 的工作原理 字节码执行&#xff1a;JIT 编译器首先会以字节码的形式执行代码&…

BERT训练环节(代码实现)

1.代码实现 #导包 import torch from torch import nn import dltools #加载数据需要用到的声明变量 batch_size, max_len 1, 64 #获取训练数据迭代器、词汇表 train_iter, vocab dltools.load_data_wiki(batch_size, max_len) #其余都是二维数组 #tokens, segments, vali…

WPF DataGridTextColumn 时间列格式设置

WPF DataGridTextColumn 时间列格式设置 可以使用 Binding.StringFormat 来进行设置&#xff1a; <DataGridTextColumn Header"记录时间" Binding"{Binding ErrTime,StringFormatyyyy年MM月dd日 HH:mm:ss}"></DataGridTextColumn>

CentOS 替换 yum源 经验分享

视频教程在bilibili:CentOS 替换 yum源 经验分享_哔哩哔哩_bilibili问题原因 解决方法 1. 进入镜像目录 [rootlocalhost ~]# cd /etc/yum.repos.d/ 2.备份文件 [rootlocalhost yum.repos.d]# rename repo bak * 3.寻找阿里镜像源复制 https://developer.aliyun.com/mirror/ …

【数据结构】剖析二叉树(Binary Tree)

目录 &#x1f4af;引言 &#x1f4af;二叉树的定义与基本概念 &#xff08;一&#xff09;定义 &#xff08;二&#xff09;节点结构 &#xff08;三&#xff09;二叉树的形态 &#x1f4af;二叉树的遍历 &#xff08;一&#xff09;前序遍历&#xff08;Preorder Trav…

ThinkPHP一对多的关联模型运用

一、序言 最近在写ThinkPHP关联模型的时候一些用法总忘&#xff0c;我就想通过写博客的方式复习和整理下一些用法。 具体版本&#xff1a; topthink/framework&#xff1a;6.1.4topthink/think-orm&#xff1a;2.0.61 二、实例应用 1、一对多的关联 本文案例&#xff1a;一个用…

开创远程就可以监测宠物健康新篇章

在宠物健康监测的新纪元&#xff0c;智能听诊器凭借其先进技术&#xff0c;正逐步改变我们对宠物健康监护的传统认知。这不仅是一款监测工具&#xff0c;而是宠物健康管理的得力助手&#xff0c;为宠物主人和兽医提供前所未有的洞察力和便捷性。 深度学习算法&#xff1a;智能…

uniapp生物识别示例(人脸识别、指纹识别)

准备工作&#xff1a; mainfest.json设置勾选&#xff1a; 勾选完成后打 App自定义调试基座测试包 示例代码&#xff1a; <template><view class"content"><button v-if"supportSoterAuthenticationArray.includes(facial)" click"…