From the course: Complete Guide to Parallel and Concurrent Programming with C++
Unlock this course with a free trial
Join today to access over 24,800 courses taught by industry experts.
Atomic objects: C++ demo - C++ Tutorial
From the course: Complete Guide to Parallel and Concurrent Programming with C++
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 a 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 6 and I don't have any locks in place to protect it with mutual exclusion, when I run this program, it has a data race that produces an incorrect result, less…
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.