Double-Ended Queues using std::deque

Thread safety of std::deque

Is std::deque thread-safe? Can multiple threads access a deque concurrently?

Vector art representing computer hardware

In C++, std::deque is not thread-safe by default. Multiple threads accessing a deque concurrently can lead to race conditions and undefined behavior, unless the access is properly synchronized.

The C++ standard specifies that concurrent access to a standard library container is only safe under certain conditions:

  1. Multiple threads can read from a deque concurrently.
  2. Multiple threads can write to different deques concurrently.
  3. Multiple threads cannot simultaneously access the same deque if at least one of those accesses is a write.

Here's an example of unsafe concurrent access:

#include <deque>
#include <thread>

std::deque<int> d{1, 2, 3, 4, 5};

void pushFront() {
  d.push_front(0);  
}

void pushBack() {
  d.push_back(6);  
}

int main() {
  std::thread t1(pushFront);
  std::thread t2(pushBack);

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

  // The final state of d is undefined
}

In this example, two threads are simultaneously modifying the deque, which is not safe.

To safely access a deque from multiple threads, you need to use synchronization primitives like mutexes or locks to ensure that only one thread can access the deque at a time:

#include <deque>
#include <mutex>
#include <thread>

std::deque<int> d{1, 2, 3, 4, 5};
std::mutex m;

void pushFront() {
  std::lock_guard<std::mutex> lock(m);  
  d.push_front(0);
}

void pushBack() {
  std::lock_guard<std::mutex> lock(m);  
  d.push_back(6);
}

int main() {
  std::thread t1(pushFront);
  std::thread t2(pushBack);

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

  // The final state of d is well-defined
}

Here, a std::mutex is used with std::lock_guard to ensure that only one thread can access the deque at a time.

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