博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
C++11 多线程
阅读量:2182 次
发布时间:2019-05-01

本文共 4056 字,大约阅读时间需要 13 分钟。

Linux 程序员都用过 Pthread, 但有了 C++11 的 std::thread以后,你可以在语言层面编写多线程程序了,直接的好处就是多线程程序的可移植性得到了很大的提高,所以作为一名 C++ 程序员,熟悉 C++11 的多线程编程方式还是很有益处的。

 C++11 多线程相关的头文件

C++11 新标准中引入了四个头文件来支持多线程编程,他们分别是<atomic> ,<thread>,<mutex>,<condition_variable>和<future>

  • <atomic>:该头文主要声明了两个类, std::atomic 和 std::atomic_flag,另外还声明了一套 C 风格的原子类型和与 C 兼容的原子操作的函数。
  • <thread>:该头文件主要声明了 std::thread 类,另外 std::this_thread 命名空间也在该头文件中。
  • <mutex>:该头文件主要声明了与互斥量(mutex)相关的类,包括 std::mutex系列类,std::lock_guard, std::unique_lock, 以及其他的类型和函数。
  • <condition_variable>:该头文件主要声明了与条件变量相关的类,包括 std::condition_variable 和 std::condition_variable_any。
  • <future>:该头文件主要声明了 std::promise, std::package_task 两个 Provider 类,以及 std::future 和 std::shared_future 两个 Future 类,另外还有一些与之相关的类型和函数,std::async()函数就声明在此头文件中。

std::thread "Hello world"

下面是一个最简单的使用 std::thread 类的例子:

#include 
#include
#include
// std::cout#include
// std::threadvoid thread_task() { std::cout << "hello thread" << std::endl;}int main(int argc, const char *argv[]){ std::thread t(thread_task); t.join(); return EXIT_SUCCESS;}

Makefile 如下:

all:ThreadCC=g++CPPFLAGS=-Wall -std=c++11 -ggdbLDFLAGS=-pthreadThread:Thread.o    $(CC) $(LDFLAGS) -o $@ $^Thread.o:Thread.cc    $(CC) $(CPPFLAGS) -o $@ -c $^

注意在 Linux GCC4.6 环境下,编译时需要加 -pthread,否则执行时会出现:

$ ./Threadterminate called after throwing an instance of 'std::system_error'  what():  Operation not permittedAborted (core dumped)

原因是 GCC 默认没有加载 pthread 库,据说在后续的版本中可以不用在编译时添加 -pthread 选项。

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

std::thread 构造

default (1)
thread() noexcept;
initialization (2)
template 
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 
#include
#include
#include
#include
#include
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';}

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 
#include
#include
// std::chrono::seconds#include
// std::cout#include
// std::thread, std::this_thread::sleep_forvoid 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;}

其他成员函数

转载地址:http://dttkb.baihongyu.com/

你可能感兴趣的文章
Leetcode C++《热题 Hot 100-22》2.两数相加
查看>>
Leetcode C++《热题 Hot 100-23》3.无重复字符的最长子串
查看>>
Leetcode C++《热题 Hot 100-24》5.最长回文子串
查看>>
Leetcode C++《热题 Hot 100-26》15.三数之和
查看>>
Leetcode C++《热题 Hot 100-28》19.删除链表的倒数第N个节点
查看>>
Leetcode C++《热题 Hot 100-29》22.括号生成
查看>>
Leetcode C++《热题 Hot 100-44》102.二叉树的层次遍历
查看>>
Leetcode C++《热题 Hot 100-47》236.二叉树的最近公共祖先
查看>>
Leetcode C++《热题 Hot 100-48》406.根据身高重建队列
查看>>
《kubernetes权威指南·第四版》第二章:kubernetes安装配置指南
查看>>
Leetcode C++《热题 Hot 100-49》399.除法求值
查看>>
Leetcode C++《热题 Hot 100-51》152. 乘积最大子序列
查看>>
Leetcode C++ 《第181场周赛-1》 5364. 按既定顺序创建目标数组
查看>>
Leetcode C++ 《第181场周赛-2》 1390. 四因数
查看>>
阿里云《云原生》公开课笔记 第一章 云原生启蒙
查看>>
阿里云《云原生》公开课笔记 第二章 容器基本概念
查看>>
阿里云《云原生》公开课笔记 第三章 kubernetes核心概念
查看>>
阿里云《云原生》公开课笔记 第四章 理解Pod和容器设计模式
查看>>
阿里云《云原生》公开课笔记 第五章 应用编排与管理
查看>>
阿里云《云原生》公开课笔记 第六章 应用编排与管理:Deployment
查看>>