Skip to Content
C++程序设计语言(第4部分:标准库)(原书第4版)
book

C++程序设计语言(第4部分:标准库)(原书第4版)

by 本贾尼 斯特劳斯特鲁普
August 2021
Intermediate to advanced
450 pages
6h 57m
Chinese
Pearson
Content preview from C++程序设计语言(第4部分:标准库)(原书第4版)

42.2 线程

thread是计算的概念在计算机硬件层面的抽象。C++标准库thread的设计目标是与操作系统线程形成一对一映射。当程序中多个任务需要并发进行时,我们就可以使用thread。在一个多处理单元(“核心”)的系统上,thread可以充分利用这些单元。所有thread工作于同一个地址空间中。如果你希望硬件能防止数据竞争,则应使用进程。thread间不共享栈,因此局部变量不会产生数据竞争问题,除非你不小心将一个局部变量的指针传递给其他thread。我们要特别小心lambda中的引用方式的上下文绑定(见11.4.3节)。深思熟虑地、小心地共享栈内存空间很有用,也很常见。例如,我们可能将一个局部数组的不同部分传递给一个并行排序函数。

如果一个thread不能继续前进(比如,因为它遇到了一个其他thread所拥有的mutex),我们称它处于阻塞(blocked)或睡眠(asleep)状态。

一个thread表示一个系统资源,一个系统线程(system thread),甚至可能有专用硬件:

因此,thread可以移动但不能拷贝。

作为一个源被移动后,thread就不再表示一个计算线程了。特别是,它不能被join()了。

操作thread::hardware_concurrency()报告硬件支持多少个任务同时执行。其具体含义依赖于机器体系结构,但通常小于操作系统提供的线程数(例如,通过时间多路复用或时间分片),有时大于处理器数或“核心数”。例如,我的双核小笔记本报告有四个硬件线程(它使用了超线程(hyper-threading)技术)。 ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.

Read now

Unlock full access

More than 5,000 organizations count on O’Reilly

AirBnbBlueOriginElectronic ArtsHomeDepotNasdaqRakutenTata Consultancy Services

QuotationMarkO’Reilly covers everything we've got, with content to help us build a world-class technology community, upgrade the capabilities and competencies of our teams, and improve overall team performance as well as their engagement.
Julian F.
Head of Cybersecurity
QuotationMarkI wanted to learn C and C++, but it didn't click for me until I picked up an O'Reilly book. When I went on the O’Reilly platform, I was astonished to find all the books there, plus live events and sandboxes so you could play around with the technology.
Addison B.
Field Engineer
QuotationMarkI’ve been on the O’Reilly platform for more than eight years. I use a couple of learning platforms, but I'm on O'Reilly more than anybody else. When you're there, you start learning. I'm never disappointed.
Amir M.
Data Platform Tech Lead
QuotationMarkI'm always learning. So when I got on to O'Reilly, I was like a kid in a candy store. There are playlists. There are answers. There's on-demand training. It's worth its weight in gold, in terms of what it allows me to do.
Mark W.
Embedded Software Engineer

You might also like

算法精讲视频课程:24篇系列讲座

算法精讲视频课程:24篇系列讲座

罗伯特·塞奇威克, 凯文·韦恩(Kevin Wayne)
可编程网络自动化

可编程网络自动化

Jason Edelman, Scott S. Lowe, Matt Oswalt
C语言核心技术(原书第2版)

C语言核心技术(原书第2版)

Peter Prinz, Tony Crawford
Go程序设计语言

Go程序设计语言

艾伦A. A.多诺万, 布莱恩W. 柯尼汉

Publisher Resources

ISBN: 9787111544395