Introduction to Stacks using std::stack

Thread safety with std::stack

Is std::stack thread-safe? Can I safely access a stack concurrently from multiple threads?

Illustration representing computer hardware

No, std::stack is not thread-safe by itself. If you access a std::stack concurrently from multiple threads and at least one of those accesses is a write (i.e., modifying the stack), you need to manually synchronize access to the stack to avoid data races and undefined behavior.

Here's an example that demonstrates the problem:

#include <stack>
#include <thread>

std::stack<int> globalStack;

void pushToStack(int value) {
  globalStack.push(value); }

void popFromStack() {
  if (!globalStack.empty()) {
    globalStack.pop();
  }
}

int main() {
  std::thread t1(pushToStack, 1);
  std::thread t2(popFromStack);

  t1.join();
  t2.join();
}

In this code, t1 is trying to push to the stack while t2 is trying to pop from it, concurrently. This is a classic data race. The behavior is undefined and can lead to hard-to-debug problems.

To make this code safe, you need to use a synchronization primitive like a mutex:

#include <mutex>
#include <stack>
#include <thread>

std::stack<int> globalStack;
std::mutex stackMutex;

void pushToStack(int value) {
  stackMutex.lock();
  globalStack.push(value);
  stackMutex.unlock();
}

void popFromStack() {
  stackMutex.lock();
  if (!globalStack.empty()) {
    globalStack.pop();
  }
  stackMutex.unlock();
}

int main() {
  std::thread t1(pushToStack, 1);
  std::thread t2(popFromStack);

  t1.join();
  t2.join();
}

Now, only one thread can access the stack at a time, preventing data races.

If you need a thread-safe stack-like data structure, you can consider using std::queue with a std::mutex and a std::condition_variable for synchronization, or use a lock-free stack implementation.

Remember, whenever you have shared mutable state accessed by multiple threads, you need to synchronize access to that state. The C++ standard library containers, including std::stack, are not thread-safe by themselves.

Answers to questions are automatically generated and may not have been reviewed.

Free, Unlimited Access

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Screenshot from Warhammer: Total War
Screenshot from Tomb Raider
Screenshot from Jedi: Fallen Order
Contact|Privacy Policy|Terms of Use
Copyright © 2024 - All Rights Reserved