From the course: Parallel and Concurrent Programming with C++ Part 1
Unlock the full course today
Join today to access over 22,600 courses taught by industry experts or purchase this course individually.
Atomic objects: C++ demo - C++ Tutorial
From the course: Parallel and Concurrent Programming with C++ Part 1
Atomic objects: C++ demo
- [Instructor] Using a lock to protect a shared variable with mutual exclusion works. But if you're only doing simple operations, like incrementing a variable's value, then the simpler solution is to use C++ atomic types which encapsulate a value and synchronize access to it to prevent a data race. If I scroll down this documentation page, I see a variety of atomic types including atomic Booleans, characters, integers, long values, and so on. Continuing down the page is a list of functions of the atomic object which implement many of the common operations. To demonstrate using atomic objects, I'm going to modify the previous example code to demonstrate a data race which has two parallel threads incrementing a count variable 10 million times. I should get an output of 20 million, but since I'm using a regular integer on line six, and I don't have any locks in place to protect it with mutual exclusion. When I run…
Practice while you learn with exercise files
Download the files the instructor uses to teach the course. Follow along and learn by watching, listening and practicing.