🦖
Wii
  • 原码补码反码
  • Archive
    • Job
      • Learn
      • 算法
      • Company
        • HundunDaxue
      • Company
      • 基础
        • 原码补码反码
      • 项目经验
      • require
    • Hobbies
      • Physics
        • 上帝粒子
        • 概述
        • 时间
      • Movie
        • MovieList
      • Psychology
        • Psychology
        • Chenli
          • ChenliLivingRoom
      • Philosophy
        • Philosophy
        • Conceptions
        • 导言
      • Travel
        • City
          • 昆明
          • 沈阳
        • articles-check-list
      • Sports
        • Swimming
        • Skiing
      • Earth
        • Ocean
          • Biology
      • Read
        • BookList
        • 道德经
        • BookToRead
      • Music
        • sort
      • PickUp
        • SoldiersSortie
    • Care
      • Illness
        • cold
        • 腹泻
        • acne
        • EmotionalControl
        • 咽炎
        • Anemia
      • Foods
        • 破壁机
          • 食谱
      • I
      • WishList
      • WithL
        • MF
          • LY
    • Wfw
      • QA
    • Mac
      • Brew
        • 软件安装目录
      • Usage
        • RunScriptAsRootOnBoot
        • Mac-Config
      • 制作启动U盘
      • Software
        • IntelliJIDEALicenseServer
          • run-license-server
    • PlantUML
      • plantuml
    • Windows
      • Windows常用命令
      • PowerShell
        • powershell 命令
      • Cmder
      • MTP服务驱动无法安装
    • English
      • 英语阅读2016-07-29
      • 英语阅读2016-08-11
    • Tools
      • Plantuml
        • Setup
      • Eclipse
        • Eclipse
        • Eclipse常见问题
      • CommonHotkey
      • Jetbrain
        • JetbrainIDEs
      • VSCode
      • SublimeText
        • 格式化代码
    • I
      • WHATIAM
    • Device
      • Netgear
        • Astrill
      • RPi
        • Hardware
    • AwesomeSoftware
    • RESTful
    • Course
      • 自然辩证法
        • 我国在生态文明建设中存在的困境及解决对策
        • 工程师应该具有的基本道德素养
        • 科学文化与人文文化的关系
      • 英语写作
        • Description
      • 分布式系统
        • 分布式系统概论
      • 英语口语
        • 辩论赛
    • CloudLib
      • 推荐0.1
    • Project
      • README
        • emq
          • Emq架构
        • 启动
        • Hikvision
          • TimeSetting
    • Efficient
    • Neu
      • IpCamera
        • live
        • ffmpeg
    • Matlab
      • Matlab 2016b 破解
    • SchoolWork
      • 学术道德与学术规范
    • git-push
  • Coding
    • Design Pattern
      • 设计模式笔记_四_工厂模式
      • 设计模式笔记_六_命令模式
      • 设计模式笔记_三_装饰者模式
      • 设计模式入门
      • 设计模式笔记_八_模板方法模式
      • 设计模式笔记_一_策略模式
      • 设计模式笔记_五_单件模式
      • 设计模式笔记_七_适配器模式与外观模式
      • 设计模式笔记_二_观察者模式
      • 设计模式笔记_十_状态模式
      • 设计模式笔记_九_迭代器与组合模式
    • C++
      • Notes
        • Practice
          • Logger
        • Thread
          • PosixThreadPrograming
          • ThreadNote
        • Features
          • FuturePromise
          • Lambda
        • STL
          • STLPractice
          • 迭代器
          • UnorderedMapSet
          • Containor
          • STL
          • Vector
        • CMake
          • Startup
          • CMakeExample
          • CMake
          • CMakeUsage
          • CMakeKnowledge
        • Mutex
        • Gdb
          • Gdb
        • LanguageNotes
          • Pointer
          • String
          • Functions
          • 友元
          • IO
          • OOP
          • Exceptions
          • Basic
          • 初始化
          • Random
          • 模板函数
        • Glog
          • glog
        • Thrift
          • Thrift
        • Valgrind
          • valgrind
        • 动态库 & 静态库
        • BookNotes
          • AboutC++
        • LRvalues
      • map
      • protobuf
      • Build
      • Seastar
        • Notes
          • std::move
          • Introduce
          • Install
            • BuildAndInstall
          • Steps
          • cmd
      • Tricks
      • Map
      • CommonOperation
      • FreqAlgorithm
    • Tools
      • Git
        • GitExamples
        • GitUsage
        • GitKnowledge
        • GitIgnoreExample
        • DeleteBigFileFromHistory
      • Vim
        • VimTips
        • 安装
        • Vim-Usage
        • Plugins
        • Vim-Config
      • SVN
        • svn服务器搭建
        • svn
    • Scala
      • Notes
        • Scala-模式匹配
        • Scala: 隐式
        • Scala-符号语法
        • Scala-函数
        • Scala面向对象编程
        • Scala 函数式编程
        • Scala:zipWithIndex
        • Future
        • Scala-语法
        • Scala-基础
      • DateTime
      • 规范
    • Python
      • Notes
        • BookNotes
          • 生成器
          • 垃圾回收机制
          • 数据结构
          • 数据类型
          • RegularExpression
          • 迭代器
          • NetworkProgramming
          • 函数式编程
          • 上下文管理器
          • PythonDataModel
          • 运算符
          • 魔术方法
          • 面向对象
          • 装饰器
          • 模块
          • MultithreadProgramming
          • 异常
          • 函数
        • Modules
          • stack
          • Datetime
          • shutil:文件操作
          • logging
          • urllib
          • Re
          • 容器数据类型
          • TypeError
          • str
          • queue
          • urllib-and-requests
          • Exception
          • path
          • os
        • Others
          • PythonSerialization
          • Python函数的docstring
          • PIL
          • type-cast
          • operations
          • Python-类
          • 组及命名组匹配
          • Package
          • jieba分词
          • logging模块
          • Python
          • print
        • Examples
          • 文件读取写入
          • 命名
          • 递归更改文件为windows合法名称
          • 定制命令行运行方式
          • Python处理Excel文件(xlsx文件格式)
          • 读取ini配置文件
          • tor代理
          • 添加父目录到Path
        • CommonTips
        • CodingStandards
          • python注释
          • PEP-8
      • Django
        • DjangoDocs
          • making queries
          • 设置media路径
          • models
          • manage.py使用
          • template
          • view
          • forms
          • setting.py 文件配置说明
          • nginx-deploy
          • 使用pymysql
          • 自定义tags和filters
          • admin-interface
        • DjangoRestFramework
          • Customer Permissions
          • Serializers
          • FileField绝对路径问题
          • DjangoRestFrameworkNotes
          • ViewSet
        • DjangoNotes
          • Model对象转化为Dict
          • QuerySet
      • Scrapy
        • Scrapy
        • Spider
        • Scrapy安装出错
        • Selector
        • Scrapy模拟登陆
      • Job
        • 字典
      • Pandas
        • pandas
        • PandasExamples
      • VirtualEnv
        • virtualenv
      • Numpy
        • NumpyUsage
        • numpy
      • Matplotlib
        • MatplotlibNotes
        • MatplotlibUsage
      • Database
        • 获取表字段
      • Pip
        • 更改源
      • Scipy
        • scipy
    • Web
      • 插件
        • bootstrap-table
          • bootstrap-table
        • bootstrap
          • 模态框
        • requirejs
          • requirejs
        • toastr
          • toastor
      • Koa
        • Notes
          • KoaNotes
      • SCSS
        • 常用标签
        • Watch
      • Vue
        • Notes
          • 路由
          • 参考
          • 组件
          • Plugins
          • Vuex
          • StartUp
      • 样式
      • CSS
        • CSS
      • 排版
      • Notes
        • 跨域访问
      • Hexo
        • HexoUsage
      • Nodejs
        • Koa
          • jest
          • ParamValidate
        • 仓库镜像
      • Express
        • Express
        • Jade
          • Jade
      • Canvas
        • Canvas
    • Basic
      • Data Structure
        • Heap
          • Heap
        • Tree
          • Tree
        • Benchmark
          • map
      • Boolean
      • MultithreadProgramming
      • Software Engineering
        • UML
          • UML
      • OOP
      • 介绍
    • Antlr
      • Example
      • Grammar
      • Antlr
    • Java
      • Library
        • MyBatis
          • generator
            • mybatis配置详解
          • mybatis-获取自增ID
          • mybatis
          • problems
        • log4j
          • Usage
      • Maven
        • MavenUsage
        • Maven
        • MavenProject
        • 项目RUL路径问题
        • MavenPom
        • Settings
        • PomCommon
        • PomExample
      • Notes
        • Features
          • Reflect
          • Java函数式编程
          • toMap
          • Closeable & AutoCloseable & Flushable
          • Annotations
        • Common
        • ThinkingInJava
          • 控制执行流程
          • 接口
          • 复用类
          • 内部类
          • 操作符
          • 访问权限控制
          • 一切都是对象
          • 多态
          • 初始化与清理
          • 对象导论
        • SwordToOffer
        • Network
        • Thread
          • ThreadPool
        • Basic Library
        • Collections
          • List Interface
        • CommandLine
        • Project Common
        • JavaLang
      • JVM
        • Monitor
          • Jmap
          • mat
          • Jstat
          • Monitor
        • Notes
          • JVM
        • GC
          • GC
          • Shenandoah
            • Shenandoah
        • JVM
    • Algorithm
      • Code
        • LeetCode
          • Python
            • 0000-0050
              • 0005
              • 0030
        • SwordToOffer
          • SwordToOffer
      • AlgorithmSummary
      • Classics
        • string
          • KMP
        • Other
          • FullPermutation
        • 链表
        • Sort
          • Sort
      • Other
        • README
      • Notes
        • Math
          • 两点计算直线方程
    • Go
      • Notes
        • Go Project Layout
        • Install
        • Startup
      • Basic
        • Startup
        • Types
    • JavaScript
      • MasonryLayouts
      • jquery
      • Notes
        • Promise
      • js
    • Android
      • SDK
        • 打开SDK Manager
    • C#
      • WebBrowser
      • c#图片
      • 跨线程访问控件
    • Knowledge
      • 函数式编程
      • 设计框架
    • Rules
      • Rules
    • React
      • ReactNative
        • React Native Navigation
        • 打包Apk
        • ReactNative
      • React
        • README
    • RegExp
      • 正则表达式
    • WeChatApp
      • 登陆
    • Node
      • Notes
        • StartUp
  • Computer Science
    • ICS Security
      • 工控网络
      • 工业控制系统
      • HoneyPot
        • 蜜罐软件
          • Honeyd
      • 工业以太网
      • CNVD
        • 环境及依赖
      • 现有蜜罐系统及工具
      • 工控系统安全措施
      • 蜜网
      • 蜜罐
      • 工控安全相关概念
    • Data Analysis
      • Data Mining
        • Notes
          • Data_Preprocessing
          • 数据预处理
          • 认识数据
          • Mining_Modeling
          • 数据探索
          • Python_Data_Mining_Functions
          • Python数据分析平台搭建
          • Reference_Books
          • 数据分析与挖掘基础
        • Jupyter
          • show
            • mean
      • Hadoop
        • Hadoop权威指南:数据完整性
        • Hadoop权威指南: I/O操作序 - 列化
        • Hadoop权威指南-从Hadoop URL读取数据
        • Hadoop权威指南:FSDataInputStream对象
        • HDFS常用命令
        • Hadoop权威指南:HDFS-数据流
        • Hadoop权威指南:通过distcp并行复制
        • Hadoop权威指南:压缩
        • Hadoop权威指南:HDFS-Hadoop存档
        • 解决使用Idea/Eclipse编写Hadoop程序包依赖问题
        • HDFS
        • Hadoop-命令
        • 简单javaHadoop应用程序从打包到提交运行
        • Hadoop权威指南:HDFS-写入数据
        • Hadoop权威指南:HDFS-目录,查询文件系统,删除文件
        • HadoopInputFormat-OutputFormart
        • Hadoop-HDFS命令行接口
        • Hadoop权威指南-MapReduce应用开发
        • Linux下使用javac编译Hadoop程序
        • Hadoop权威指南:通过FileSystem API读取数据
        • Hadoop专有数据类型
      • Spark
        • Spark计算模型
        • Spark-入门二
        • 安装Hadoop及Spark(Ubuntu 16.04)
        • Spark:核心概念简介
        • Spark:控制日志输入
        • Spark - RDD编程
        • Spark工作机制
        • Spark-一个独立应用
        • Spark
        • Spark:使用Spark Shell的两个示例
    • Linux
      • Notes
        • BuildInCommand
          • ls
          • ip
          • ftp
          • 目录栈操作
          • scp
          • expect
            • expect示例
            • expect手册
            • expect笔记
          • ps
          • vsftpd
          • wget
          • 压缩程序
            • zip_unzip
            • tar
            • p7zip
          • 部署web服务
          • avidemux
          • cat
          • Awk
          • find
          • pssh使用
          • grep
          • sed
          • 路径
          • 通用命令
          • 安装JDK
          • 进程管理
          • network
          • rsync
          • cron
          • 示例
          • 用户管理
          • supervisor
        • Common
        • TestFileProcess
          • 替换文件内容
        • Commonds
        • Permissions
      • Ubuntu
        • Ubuntu 服务器配置部署
        • Ubuntu笔记
        • Ubuntu网络配置
        • Ubuntu 16.04 几个国内源
      • Script
        • ShellProgramming
        • ShellExamples
        • ShellCommands
      • CentOS
        • Centos笔记
        • 源
        • CentOS-Network-Config
        • CentOS-Security
      • Squid
        • BuildByDocker
        • Squid
      • Problem
        • 常见错误
      • Linux
        • Linux-c-cpp
        • Linux
        • Linux-NetworkProgramming
      • Codes
        • cron-test-01
      • Software
        • Shortcut key
        • Anaconda
      • Make
        • tricks
      • Deepin
        • 安装docker
      • SRE
        • CommonCommand
    • Cloud Computing
      • OpenStack
        • Fuel离线安装OpenStack
        • 验证网络
        • OpenStackNotes
    • Network
      • TCP/IP
      • 套接字
      • OSI模型
    • Data mining
      • StartUp
    • Machine Learning
      • Notes
        • 决策树学习-周志华
        • 神经网络-周志华
        • 概念学习和一般到特殊序
        • MachineLearningProblems
        • Math
          • 概率论与数理统计
          • 数学概念
          • KKT条件
          • 最优化问题
          • 优化算法
          • 最小二乘
        • 模型评估与选择
        • 引言
        • 过拟合处理
        • StatisticalLearningMethod
          • 统计学习方法概论
          • 感知机
        • 评估假设
        • Code
          • FeatureEngineering
            • Iris
        • 概念
        • SVM
        • FeatureEngineering
        • 神经网络
        • 决策树学习
        • MachineLearningKnowledge
        • 线性模型
        • 术语概念
        • 拉格朗日乘子法
      • route
      • Jupyter
        • JupyterUsage
      • Anaconda
        • AnacondaUsage
      • Coursera
        • Week01
      • ScikitLearn
        • FitTransform
        • Preprocessing
      • Octave
        • Octave
    • Search
      • Lucene
        • Api
        • Concepts
    • Virtualization Tech
      • Docker
        • dockerNetwork
        • Ubuntu
        • DockerUsage
        • Mac OS
    • Database
      • MySQL
        • Mysql Cluster
        • mysql-cluster
        • mysql
      • 部署phpmyadmin
      • SQL
      • SQL
        • SQLStatement
    • Concepts
      • Other
      • Mohout
      • LDA
    • Distributed System
      • Concepts
        • TODO
        • TODO
    • Recommend System
      • DataPipline
        • DataBus
        • 系统
    • OS
      • OS-Code
      • Notes
        • Introduce
        • ProcessManagement
        • Kernel
    • Deep Learning
      • Code
        • README
      • Notes
        • Conceptions
        • 神经网络
        • LeNet5
        • CNN
      • Tensorflow
        • Notes
          • Tensorflow
          • tensorflow开始
        • Anaconda
    • Media
      • FFmpeg
        • LiveStream
          • run
    • Spider
      • Selenium
        • Selenium
    • IoT
      • emq
        • Authentication
    • Big Data
      • Hadoop
        • MR 作业
  • Architecture
    • Storage
      • Mongodb
        • Mongodb
        • Failed to unlink socket file
      • Pegasus
        • Pegasus
        • ShellTools
      • Rocksdb
        • RocksJava
        • RocksDB
        • 本地缓存
      • Redis
        • Install
        • RedisUsage
      • 基本要素
      • HBase
        • HBase
    • MQ
      • Kafka
        • VersionCompare
        • Deploy
        • cppkafka
        • CommandLineTools
        • OffsetManage
        • Attentions
        • Notes
        • QA
    • Framework
      • Java
        • Dubbo
          • Annotation
          • 简介
        • Spring
          • SpringTest
          • 常见错误
          • TransactionRollback
          • FileUpload
          • SpringMVCNote
          • IoC
          • Start
          • Notes
            • Config
          • Spring
          • springmvc
          • Modules
        • Rose
          • Get request body
        • Netty
          • Netty
        • SpringBoot
          • SpringBoot
      • Esper
        • Documents
          • Keyed Segmented Context
          • 01 - Getting Started
          • 02 - Event Representations
          • 03 - Processing Modal
      • Swagger
        • Swagger
    • RPC
      • Thrift
        • Notes
          • Set fields
          • ThriftTyps
        • BuildFromSource
        • ThriftUsage
        • Install
      • ProtocolBuffer
        • 减少内存拷贝
        • UsageExample
        • Arena
        • ProtocolBuffer
    • Distribution
      • CAP
    • Streaming
      • Spark
        • Init
      • MapReduce
      • Spark
    • Nginx
      • Nginx knowledge
      • nginx-configurtion
      • 403
      • nginx解析php文件时502
    • Governance
      • Consul
      • Zookeeper
        • Zookeeper
      • MicroServiceArchitecture
      • 依赖
    • Conceptions
      • CloudNative
    • Kibana
      • Query
    • Performance Optimizaition
      • Notes
        • Conceptions
        • CPUAffinity
  • Math
    • Probability Theory
      • 一些概率分布
    • Statistics
      • 统计量与估计量
    • Other
      • 排列组合
  • Tools
    • Markdown
      • syntax
    • Jetbrains
      • Jetbrains
    • Zsh
      • Install
  • TODO
由 GitBook 提供支持
在本页
  • C++11 之前
  • C++11
  • 构造函数
  • 赋值操作
  • 其他成员函数
  • 终止线程
  • std::this_thread
  • Examples
  • 主线程早于子线程退出
  • 线程作为方法参数
  • 判断线程是否有效
  • PS
  • 线程+lambda
  • 参考
  • 编译

这有帮助吗?

  1. Coding
  2. C++
  3. Notes
  4. Thread

ThreadNote

C++11 之前

#include <pthread.h>
pthread_create (thread, attr, start_routine, arg)

参数

说明

thread

子例程返回的新线程的不透明的唯一标识符。

attr

一个opaque属性对象,可用于设置线程属性。您可以指定线程属性对象,或者为默认值指定NULL。

start_routine

线程创建后将执行的C ++例程。

arg

可以传递给start_routine的单个参数。它必须通过引用传递为void类型的指针转换。如果不传递参数,则可以使用NULL。

C++11

#include <thread>
std::thread nth(&ctr::Class::func, this);        // 创建运行对象成员函数的线程
std::thread nth(func, "HELLO");

构造函数

构造函数

说明

备注

thread() noexcept;

默认构造函数

创建空的std::thread执行对象

template explicit thread (Fn&& fn, Args&&... args);

初始化

创建std::thread对象,该对象可被joinable,信产生的线程会调用fn函数,该函数的参数由args给出

thread (const thread&) = delete;

拷贝构造(被禁用 - delete)

意味着std::thread对象不可被拷贝

thread (thread&& x) noexcept;

移动构造

调用成功之后x不代表任何std::thread执行对象

Example

#include <iostream>
#include <utility>
#include <thread>
#include <chrono>
#include <functional>
#include <atomic>

void f1(int n)
{
    for (int i = 0; i < 5; ++i) {
        std::cout << "Thread " << n << " executing\n";
        std::this_thread::sleep_for(std::chrono::milliseconds(10));
    }
}

void f2(int& n)
{
    for (int i = 0; i < 5; ++i) {
        std::cout << "Thread 2 executing\n";
        ++n;
        std::this_thread::sleep_for(std::chrono::milliseconds(10));
    }
}

int main()
{
    int n = 0;
    std::thread t1; // t1 is not a thread
    std::thread t2(f1, n + 1); // pass by value
    std::thread t3(f2, std::ref(n)); // pass by reference
    std::thread t4(std::move(t3)); // t4 is now running f2(). t3 is no longer a thread
    t2.join();
    t4.join();
    std::cout << "Final value of n is " << n << '\n';
}
#include <iostream>
#include <unistd.h>
#include <thread>
#include <unistd.h>

using namespace std;

class A {
public:
    void f(string str) {
        cout << "A::f() " << str << endl;
        sleep(3);
    }

    void fn() {
        cout << "A::fn()" << endl;
        sleep(3);
    }
};

void f(string str) {
    cout << "f(string str)" << str << endl;
    sleep(3);
}

void fn() {
    cout << "fn()" << endl;
    sleep(3);
}

int main() {
    A a;
    std::thread nth(f, "Hello");        // 有参数的方法
    sleep(1);
    std::thread nfth(fn);                // 无参方法
    sleep(1);
    std::thread nfthc(&A::f, &a, "hello");    // 有参类方法

    while (true) {}
    return 0;
}
/** Output
f(string str)Hello
fn()
A::f() hello
*/
// constructing threads
#include <iostream>       // std::cout
#include <atomic>         // std::atomic
#include <thread>         // std::thread
#include <vector>         // std::vector

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

void increase_global (int n) { for (int i=0; i<n; ++i) ++global_counter; }

void increase_reference (std::atomic<int>& variable, int n) { for (int i=0; i<n; ++i) ++variable; }

struct C : std::atomic<int> {
  C() : std::atomic<int>(0) {}
  void increase_member (int n) { for (int i=0; i<n; ++i) fetch_add(1); }
};

int main ()
{
  std::vector<std::thread> threads;

  std::cout << "increase global counter with 10 threads...\n";
  for (int i=1; i<=10; ++i)
    threads.push_back(std::thread(increase_global,1000));

  std::cout << "increase counter (foo) with 10 threads using reference...\n";
  std::atomic<int> foo(0);
  for (int i=1; i<=10; ++i)
    threads.push_back(std::thread(increase_reference,std::ref(foo),1000));

  std::cout << "increase counter (bar) with 10 threads using member...\n";
  C bar;
  for (int i=1; i<=10; ++i)
    threads.push_back(std::thread(&C::increase_member,std::ref(bar),1000));

  std::cout << "synchronizing all threads...\n";
  for (auto& th : threads) th.join();

  std::cout << "global_counter: " << global_counter << '\n';
  std::cout << "foo: " << foo << '\n';
  std::cout << "bar: " << bar << '\n';

  return 0;
}

赋值操作

赋值

说明

备注

thread& operator=(thread&& rhs) noexcept;

Move 赋值操作

如果当前对象不可 joinable,需要传递一个右值引用(rhs)给 move 赋值操作;如果当前对象可被 joinable,则会调用 terminate() 报错。

thread& operator=(const thread&) = delete;

拷贝赋值操作 [deleted]

被禁用,因此 std::thread 对象不可拷贝赋值。

#include <stdio.h>
#include <stdlib.h>

#include <chrono>    // std::chrono::seconds
#include <iostream>  // std::cout
#include <thread>    // std::thread, std::this_thread::sleep_for

void thread_task(int n) {
    std::this_thread::sleep_for(std::chrono::seconds(n));
    std::cout << "hello thread "
        << std::this_thread::get_id()
        << " paused " << n << " seconds" << std::endl;
}

int main(int argc, const char *argv[])
{
    std::thread threads[5];
    std::cout << "Spawning 5 threads...\n";
    for (int i = 0; i < 5; i++) {
        threads[i] = std::thread(thread_task, i + 1);
    }
    std::cout << "Done spawning threads! Now wait for them to join\n";
    for (auto& t: threads) {
        t.join();
    }
    std::cout << "All threads joined.\n";

    return EXIT_SUCCESS;
}

其他成员函数

  • get_id():获取线程ID

  • joinable():检查线程是否可被join

    • 检查当前的线程对象是否表示了一个活动的执行线程,由默认构造函数创建的线程是不能被 join 的

    • 如果某个线程 已经执行完任务,但是没有被 join 的话,该线程依然会被认为是一个活动的执行线程,因此也是可以被 join 的

  • detach:将当前线程对象所代表的执行实例与该线程对象分离,使得线程的执行可以单独进行。一旦线程执行完毕,它所分配的资源将会被释放。

  • swap:交换两个线程对象所代表的底层句柄(underlying handles)

  • native_handle:返回 native handle

    #include <thread>
    #include <iostream>
    #include <chrono>
    #include <cstring>
    #include <pthread.h>
    
    std::mutex iomutex;
    void f(int num)
    {
      std::this_thread::sleep_for(std::chrono::seconds(1));
    
     sched_param sch;
     int policy; 
     pthread_getschedparam(pthread_self(), &policy, &sch);
     std::lock_guard<std::mutex> lk(iomutex);
     std::cout << "Thread " << num << " is executing at priority "
               << sch.sched_priority << '\n';
    }
    
    int main()
    {
      std::thread t1(f, 1), t2(f, 2);
    
      sched_param sch;
      int policy; 
      pthread_getschedparam(t1.native_handle(), &policy, &sch);
      sch.sched_priority = 20;
      if(pthread_setschedparam(t1.native_handle(), SCHED_FIFO, &sch)) {
          std::cout << "Failed to setschedparam: " << std::strerror(errno) << '\n';
      }
    
      t1.join();
      t2.join();
    }

终止线程

#include <iostream>
#include <thread>
#include <pthread.h>

using namespace std;

void f() {
    std::this_thread::sleep_for(std::chrono::seconds(2));
    cout << "f(): mid check" << endl;
    std::this_thread::sleep_for(std::chrono::seconds(2));
    cout << "f(): done" << endl;
}

void fl() {
    while (true) {}
    cout << "fl() done" << endl;
}

int main() {
    std::thread th(f);
    thread::native_handle_type handle = th.native_handle();
    th.detach();
    std::this_thread::sleep_for(std::chrono::seconds(3));
    pthread_cancel(handle);

    std::thread thfl(fl);
    thfl.detach();
    handle = thfl.native_handle();
    cout << "Handle: " << handle << endl;
    pthread_cancel(handle);
    std::this_thread::sleep_for(std::chrono::seconds(3));

    return 0;
}
/** Output
f(): mid check
Handle: 0
*/
  • 向线程发送终止信号,并不能立即终止线程运行,只有在线程运行到检查点时,才会终止。

std::this_thread

  • get_id()

    • std::this_thread::get_id()

  • sleep_for()

    • std::this_thread::sleep_for(std::chrono::seconds(1))

    • 线程休眠某个指定的时间片

  • yield()

    • std::this_thread::yield

    • 放弃当前线程执行

  • sleep_until()

    template< class Clock, class Duration >
    void sleep_until( const std::chrono::time_point<Clock,Duration>& sleep_time );
    • 线程休眠至某个指定的时刻,该线程才被重新唤醒

  • sleep_for

Examples

主线程早于子线程退出

#include <iostream>
#include <thread>
#include <unistd.h>
#include <fstream>

using namespace std;

void f() {
    std::this_thread::sleep_for(std::chrono::seconds(1));
    cout << "f() finish" << endl;
    ofstream out("out", ofstream::out | ofstream::trunc);
    if (out.is_open()) {
        out << "HELLO";
    }
    out.close();
    return;
}

int main() {
    std::thread ths[5];
    ths[0] = std::thread();
    cout << ths[0].joinable() << endl;  // 0
    // ths[0].join();                      // terminate called after throwing an instance of 'std::system_error'; Invalid argument
    ths[1] = std::thread(f);

    ths[1].detach();
    cout << "main() finish" << endl;
    return 0;
}

/** Output
0
main() finish
*/
// 没有打印日志和生成文件

/** 将ths[1].detach()改为ths[1].join()后,Output:
0
f() finish
main() finish
*/
// 有生成文件
  • 子线程会被迫终止

线程作为方法参数

#include <iostream>
#include <thread>

using namespace std;

void fb() {
    std::this_thread::sleep_for(std::chrono::seconds(1));
    cout << "fb() done" << endl;
}

void f(thread &thd) {
    cout << thd.get_id() << endl;
    thd.join();
}

void fc(thread thd) {
    cout << thd.get_id() << endl;
    thd.join();
}

int main() {
    thread th1(fb);
    thread th2(fb);
    cout << th1.joinable() << endl;
    cout << th2.joinable() << endl;
    f(th1);        
    // fc(th1);    // ERROR: 由于thread禁用了赋值操作符,这里编译时会报错
                //           这里的th1是不能拷贝复制给形参的
    fc(std::move(th2));
    cout << th1.joinable() << endl;
    cout << th2.joinable() << endl;
    return 0;
}
/** Output
1
1
140432286369536
fb() done
fb() done
140432277976832
0
0
*/

// 一个值得注意的地方,如果main函数改为:
/**
int main() {
    thread th1(fb);
    f(th1);                    // 更改了这句的顺序
    thread th2(fb);
    cout << th1.joinable() << endl;
    cout << th2.joinable() << endl;
    fc(std::move(th2));
    cout << th1.joinable() << endl;
    cout << th2.joinable() << endl;
    return 0;
}
*/
// 那么输出为
/**
140007787820800
fb() done
0
1
140007787820800
fb() done
0
0
*/
// 有意思的是, 这里的线程ID相同, 有时间再细究, 编译器的优化?

判断线程是否有效

  • 可以通过joinable方法判断线程对象有没有被初始化

PS

  • std::thread::native_handle() 函数只有在调用join()和detach()之前有效,之后调用会返回 0,如果此时再调用 pthread_cancel() 传入返回值,试图这样来结束改进程(由于返回值是0,并不能结束该线程),会产生core dump

    #include <iostream>
    #include <thread>
    #include <pthread.h>
    
    using namespace std;
    
    void f() {
        std::this_thread::sleep_for(std::chrono::seconds(3));
    }
    
    int main() {
        std::thread th(f);
        thread::native_handle_type handle = th.native_handle();
        cout << "ID: " << handle << endl;
        cout << "Handle: " << th.get_id() << endl;
        th.join();
        cout << "Handle: " << th.native_handle() << endl;
        return 0;
    }
    /** Output
    ID: 139748843316992
    Handle: 139748843316992
    Handle: 0
    */

线程+lambda

#### example 1
$ cat 07.cpp 
#include <iostream>
#include <unistd.h>
#include <thread>

using namespace std;

int main() {
    thread th([]() {
        int i = 0;
        while (true) {
            cout << "- " << i++ << " -" << endl;
            sleep(2);
        }
    });
    th.join();
    return 0;
}
$ g++ 07.cpp -lpthread && ./a.out 
- 0 -
- 1 -

#### example 2
$ cat 13.cpp
#include <iostream>
#include <future>
#include <thread>
#include <chrono>

using namespace std;

int main() {
    std::promise<bool> p;
    thread th([&]() {
        std::this_thread::sleep_for(std::chrono::milliseconds(1000));
        cout << "set value true" << endl;
        p.set_value(true);
    });
    th.detach();
    cout << "th detach" << endl;
    p.get_future().wait();
    cout << "exit" << endl;
    return 0;
}
$ g++ 13.cpp -lpthread -std=c++11 && ./a.out
th detach
set value true
exit

参考

编译

g++ -std=c++11 -pthread 002.cpp    # g++-4.8
上一页PosixThreadPrograming下一页Features

最后更新于4年前

这有帮助吗?

线程管理
cplusplus - thread