Thread safety of std::deque

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

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.

Double-Ended Queues using std::deque

A guide to double-ended queues - a structure that behaves like a vector, specialised for manipulating objects at the edges of the collection

Questions & Answers

Answers are generated by AI models and may not have been reviewed. Be mindful when running any code on your device.

Performance differences between std::vector and std::deque
When should I use a std::deque instead of a std::vector for optimal performance?
How std::deque is implemented internally
How does a std::deque store its elements in memory?
Exception safety of std::deque operations
Which std::deque operations are exception-safe?
Benefits of using emplace over insert
What are the advantages of using emplace_front() or emplace_back() instead of push_front() or push_back()?
Iterator invalidation rules for std::deque
When do std::deque operations invalidate iterators?
Or Ask your Own Question
Get an immediate answer to your specific question using our AI assistant