Skip to Content
C++语言导学(原书第2版)
book

C++语言导学(原书第2版)

by 本贾尼 斯特劳斯特鲁普
August 2021
Intermediate to advanced
450 pages
5h 35m
Chinese
Pearson
Content preview from C++语言导学(原书第2版)

15.2 任务和thread

我们称可与其他计算并行执行的计算为任务(task)。线程(thread)是任务在程序中的系统级表示。若要启动一个与其他任务并发执行的任务,可构造一个std::thread(可在<thread>中找到),将任务作为它的参数。这里,任务是以函数或函数对象的形式实现的:

join()保证在线程完成后才退出user()。“join”一个thread表示“等待线程结束”。

一个程序的所有线程共享单一地址空间。在这一点上,线程与进程不同,进程间通常不直接共享数据。由于共享单一地址空间,因此线程间可通过共享对象(参见15.5节)相互通信。通常通过锁或其他防止数据竞争(对变量的不受控制的并发访问)的机制来控制线程间通信。

编写并发任务可能非常棘手。任务f(一个函数)和F(一个函数对象)可以这样实现:

这是一个典型的严重错误:在本例中,f和F都使用了对象cout,而没有采取任何形式的同步。输出结果将是不可预测的,而且程序每一次执行都可能得到不同结果,因为两个任务中的操作的执行顺序是不确定的。程序可能会产生下面这样“奇怪的”输出:

ostream的定义中存在可能导致程序崩溃的数据竞争,只有在C++标准中给出了专门的保证后,我们才能免受其害。

当定义一个并发程序的任务时,我们的目标是保持任务的完全隔离,唯一的例外是任务间通信的部分,而这种通信应该以一种简单而明显的方式进行。思考一个并发任务的最简单的方式是,将它看作一个可以与调用者并发执行的函数。为此,我们只需传递参数、获取结果并保证两者并不同时使用共享数据(没有数据竞争)。 ...

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

软件开发实践:项目驱动式的Java开发指南

软件开发实践:项目驱动式的Java开发指南

Raoul-Gabriel Urma, Richard Warburton
管理Kubernetes

管理Kubernetes

Brendan Burns, Craig Tracey
Python机器学习案例精解

Python机器学习案例精解

Posts & Telecom Press, Yuxi (Hayden) Liu

Publisher Resources

ISBN: 9787111633280