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:
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.
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