Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

The C++ standard library

The C++ standard library

In multithreaded programming, data synchronization and thread safety are important issues.

The C++11 standard introduced library, which provides a set of atomic operations to guarantee that access to a single piece of data in a multithreaded environment is atomic, i.e., indivisible. This avoids data races and ensures thread safety.

An atomic operation is one that cannot be interrupted by other threads during its execution.

The atomic types in the library provide such operations; they guarantee that access to shared data in a multithreaded environment is safe.

Syntax

The library provides various atomic types, includingatomic, atomic, atomic, atomic, atomic, atomic, atomic, atomic, atomic, atomic, atomic, atomic, atomic, atomic, atomic, atomic, atomic, etc.

Basic operations

Example

Below is an example usingis a simple example of the library, demonstrating how to safely update a shared counter in a multithreaded environment.

Example

#include

#include

#include

std

::

atomic

<

int

counter

(

0

)

;

// Initialize atomic counter

void

increment

(

)

{

   

for

(

int

i

=

0

;

i

<

10000

;

++

i

)

{

        counter.

fetch_add

(

1

, std

::

memory_order_relaxed

)

;

// Atomic increment

   

}

}

int

main

(

)

{

    std

::

thread

t1

(

increment

)

;

    std

::

thread

t2

(

increment

)

;

    t1.

join

(

)

;

    t2.

join

(

)

;

    std

::

cout

<<

"Final counter value: "

<<

counter

<<

std

::

endl

;

// Output the final counter value

   

return

0

;

}

Running the program above, you will see output similar to:



Final counter value: 20000

This output indicates that two threads successfully incremented the counter 10000 times each without data races.

Notes

By usinglibrary, C++ programmers can more easily write thread-safe code while maintaining high performance.