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.5 共享数据

有时任务之间需要共享数据。在此情况下,数据访问就必须进行同步,使得在同一时刻至多有一个任务能访问数据。有经验的程序员可能认为这将问题简单化了(例如,很多任务同时读取不变的数据是没有任何问题的),但请考虑如何确保在同一时刻至多有一个任务可以访问一组给定的对象。

此问题解决方法的基础是“互斥对象”mutex。一个thread使用lock()操作来获取一个互斥对象:

lck的类型被推断为scoped_lock<mutex>(参见6.2.3节)。scoped_lock的构造函数获取了互斥对象(通过调用m.lock())。如果另一个线程已经获取了互斥对象,则当前线程会等待(“阻塞”)直至那个线程完成对共享数据的访问。一旦线程完成了对共享数据的访问,Scoped_lock会释放mutex(通过调用m.unlock())。当一个mutex被释放,等待此mutex的thread会恢复执行(“被唤醒”)。互斥和锁机制在头文件<mutex>中提供。

注意RAII(参见5.3节)的使用。使用scoped_lock和unique_lock(参见15.6节)这样的资源句柄比显式对mutex加锁、解锁要更简单且更安全。

共享数据和mutex之间是一种常规的对应关系:程序员必须知道哪个mutex对应哪个数据。显然,这很容易出错,我们应努力借助多种语言特性来使这种对应关系更为清晰。例如:

对于一个名为rec的Record,不难猜测:rec.rm是一个mutex,你在访问rec其他数据前应获取这个互斥对象。可见,通过注释或好的命名方式可以提高程序的可读性。 ...

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