Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is this function with atomic thread-safe

Tags:

c++

c++11

atomic

I am trying to learn how to use atomic :)

class foo {
  static std::atomic<uint32_t> count_;
  uint32 increase_and_get() {
    uint32 t = count_++;
    return t;
  }
}

Is the function increase_and_get() thread-safe?

like image 489
WhatABeautifulWorld Avatar asked Feb 27 '13 02:02

WhatABeautifulWorld


People also ask

Is atomic thread-safe?

Atomic classes allow us to perform atomic operations, which are thread-safe, without using synchronization. An atomic operation is executed in one single machine-level operation.

Why Atomic is not thread-safe?

So atomic operations on primitive data types are a tool to achive thread safety but do not ensure thread safety automatically because you normally have multiple operations that rely on each other. You have to ensure that these operations are done without interruption eg using Mutexes.

Are functions thread-safe?

Thread safety A threadsafe function protects shared resources from concurrent access by locks. Thread safety concerns only the implementation of a function and does not affect its external interface. The use of global data is thread-unsafe.

Are atomic variables thread-safe C++?

In order to solve this problem, C++ offers atomic variables that are thread-safe. The atomic type is implemented using mutex locks. If one thread acquires the mutex lock, then no other thread can acquire it until it is released by that particular thread.


2 Answers

Yes, it is safe: the increment is atomic, and the local t cannot be altered by concurrent threads. You can further simplify your code to eliminate the temporary variable altogether:

uint32 increase_and_get() {
    return count_++;
}
like image 199
Sergey Kalinichenko Avatar answered Oct 25 '22 11:10

Sergey Kalinichenko


Yes, it would be threadsafe. Assuming of course there are no bugs in the std::atomic implementation - but it's not usually hard to get right.

This is exactly what std::atomic is meant to do.

like image 36
Mats Petersson Avatar answered Oct 25 '22 12:10

Mats Petersson