上一篇博客《C++11 并发指南一(C++11 多线程初探)》中只是提到了 std::thread 的基本用法,并给出了一个最简单的例子,本文将稍微详细地介绍 std::thread 的用法。

std::thread 在 <thread> 头文件中声明,因此使用 std::thread 时需要包含 <thread> 头文件。

std::thread 构造

default (1)
thread() noexcept;
initialization (2)
template <class Fn, class... Args>
explicit thread (Fn&& fn, Args&&... args);
copy [deleted] (3)
thread (const thread&) = delete;
move (4)
thread (thread&& x) noexcept;
  • (1). 默认构造函数,创建一个空的 thread 执行对象。
  • (2). 初始化构造函数,创建一个 thread对象,该 thread对象可被 joinable,新产生的线程会调用 fn 函数,该函数的参数由 args 给出。
  • (3). 拷贝构造函数(被禁用),意味着 thread 不可被拷贝构造。
  • (4). move 构造函数,move 构造函数,调用成功之后 x 不代表任何 thread 执行对象。
  • 注意:可被 joinable 的 thread 对象必须在他们销毁之前被主线程 join 或者将其设置为 detached.

std::thread 各种构造函数例子如下(参考):

#include <iostream>
#include <utility>
#include <thread>
#include <chrono>
#include <functional>
#include <atomic> void f1(int n)
{
for (int i = ; i < ; ++i) {
std::cout << "Thread " << n << " executing\n";
std::this_thread::sleep_for(std::chrono::milliseconds());
}
} void f2(int& n)
{
for (int i = ; i < ; ++i) {
std::cout << "Thread 2 executing\n";
++n;
std::this_thread::sleep_for(std::chrono::milliseconds());
}
} int main()
{
int n = ;
std::thread t1; // t1 is not a thread
std::thread t2(f1, n + ); // 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';
}

move 赋值操作

move (1)
thread& operator= (thread&& rhs) noexcept;
copy [deleted] (2)
thread& operator= (const thread&) = delete;
  • (1). move 赋值操作,如果当前对象不可 joinable,需要传递一个右值引用(rhs)给 move 赋值操作;如果当前对象可被 joinable,则 terminate() 报错。
  • (2). 拷贝赋值操作被禁用,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;
} /*
* === FUNCTION =========================================================
* Name: main
* Description: program entry routine.
* ========================================================================
*/
int main(int argc, const char *argv[])
{
std::thread threads[];
std::cout << "Spawning 5 threads...\n";
for (int i = ; i < ; i++) {
threads[i] = std::thread(thread_task, i + );
}
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;
} /* ---------- end of function main ---------- */

其他成员函数

获取线程 ID。
检查线程是否可被 join。
Join 线程。
Detach 线程
Swap 线程 。
返回 native handle。
检测硬件并发特性。

C++11 并发指南二(std::thread 详解)的更多相关文章

  1. C++11 并发指南二(std::thread 详解)(转)

    上一篇博客<C++11 并发指南一(C++11 多线程初探)>中只是提到了 std::thread 的基本用法,并给出了一个最简单的例子,本文将稍微详细地介绍 std::thread 的用 ...

  2. 【C/C++开发】C++11 并发指南二(std::thread 详解)

    上一篇博客<C++11 并发指南一(C++11 多线程初探)>中只是提到了 std::thread 的基本用法,并给出了一个最简单的例子,本文将稍微详细地介绍 std::thread 的用 ...

  3. C++11 并发指南五(std::condition_variable 详解)

    前面三讲<C++11 并发指南二(std::thread 详解)>,<C++11 并发指南三(std::mutex 详解)>分别介绍了 std::thread,std::mut ...

  4. C++11 并发指南三(std::mutex 详解)

    上一篇<C++11 并发指南二(std::thread 详解)>中主要讲到了 std::thread 的一些用法,并给出了两个小例子,本文将介绍 std::mutex 的用法. Mutex ...

  5. C++11 并发指南五(std::condition_variable 详解)(转)

    前面三讲<C++11 并发指南二(std::thread 详解)>,<C++11 并发指南三(std::mutex 详解)>分别介绍了 std::thread,std::mut ...

  6. C++11 并发指南三(std::mutex 详解)(转)

    转自:http://www.cnblogs.com/haippy/p/3237213.html 上一篇<C++11 并发指南二(std::thread 详解)>中主要讲到了 std::th ...

  7. 【转】C++11 并发指南五(std::condition_variable 详解)

    http://www.cnblogs.com/haippy/p/3252041.html 前面三讲<C++11 并发指南二(std::thread 详解)>,<C++11 并发指南三 ...

  8. 【C/C++开发】C++11 并发指南三(std::mutex 详解)

    本系列文章主要介绍 C++11 并发编程,计划分为 9 章介绍 C++11 的并发和多线程编程,分别如下: C++11 并发指南一(C++11 多线程初探)(本章计划 1-2 篇,已完成 1 篇) C ...

  9. C++11 并发指南六( <atomic> 类型详解二 std::atomic )

    C++11 并发指南六(atomic 类型详解一 atomic_flag 介绍)  一文介绍了 C++11 中最简单的原子类型 std::atomic_flag,但是 std::atomic_flag ...

随机推荐

  1. Python 练习: 打印0到99小于50或大于70的数字

    for i in range(100): if i < 50 or i > 70: print(i) 注意: range(100) 表示 0 到 99 个数字

  2. python中的清屏函数

    一:cmd中python的清屏函数 import os os.system("cls") cmd中演示 1.在cmd中输入命令行: 2.执行后: 3.为什么会遗留一个0? 因为函数 ...

  3. 获取url参数的方法(web)

    //获取url参数的方法(web) function GetQueryString(name) {     var reg = new RegExp("(^|&)" + n ...

  4. html学习笔记——ife task0001

    花了两三天大概看完html和css基本用法,但到自己布局的时候还是很懵不知道从哪里入手啊,就找了个简单的任务(ife2015 spring)试一下. 之前不涉及到布局的跳过,从涉及到position和 ...

  5. web全栈架构师[笔记] — 01 ECMAScript6新特性

    ES6新特性 一.变量 var:重复定义不报错:没有块级作用域:不能限制修改 let:变量,不能重复定义,有块级作用域 const:常量,不能重复定义,有块级作用域 二.函数/参数 箭头函数——简写: ...

  6. 警告!中国90%AI初创企业将在两年内落败出局

    https://mp.weixin.qq.com/s/-RkyLda1jovaHBlBTsi-BA 近年来,中国涌现了一大批AI初创企业,但AI热潮也伴随着泡沫.由于近期市场资金紧缩,投资者发出警告, ...

  7. IDEA报错: Injection of autowired dependencies failed; nested exception is java.lang.IllegalArgumentException: Could not resolve placeholder 'spring.datasource.url' in value "${spring.datasource.url}"

    运行审核流模块: 在ActivitiServiceApplication模块日志报错: Error starting ApplicationContext. To display the auto-c ...

  8. 二. Redis 安全性

    由于Redis速度相当快,当一台服务器比较好的时候,一个外部用户可以在一秒钟内进行150K(15万)次的密码尝试,因此意味着你需要设置一个非常非常强大的密码来防止暴力破解. 1.设置密码 (1). 通 ...

  9. (网页)javascript小技巧(非常全)

    事件源对象 event.srcElement.tagName event.srcElement.type 捕获释放 event.srcElement.setCapture();  event.srcE ...

  10. 安装Linux Mint 17后要做的20件事

    Linux Mint 17 Qiana Cinnamon Linux Mint 17已经发布,定名为Qiana.Mint是Linux最佳发行版之一,它定位于桌面用户,关注可用性和简洁.它携带了风格迥异 ...