// Example of using std::deque in multithreaded code
#include
#include
#include
#include
class ThreadSafeDeque {
public:
void push_back(int value) {
std::lock_guard<:mutex> lock(mutex_);
deque_.push_back(value);
}
void pop_front() {
std::lock_guard<:mutex> lock(mutex_);
if (!deque_.empty()) {
deque_.pop_front();
}
}
void print() {
std::lock_guard<:mutex> lock(mutex_);
for (const auto &val : deque_) {
std::cout << val << " ";
}
std::cout << std::endl;
}
private:
std::deque deque_;
std::mutex mutex_;
};
void thread_function(ThreadSafeDeque &ts_deque) {
for (int i = 0; i < 5; ++i) {
ts_deque.push_back(i);
}
}
int main() {
ThreadSafeDeque ts_deque;
std::thread t1(thread_function, std::ref(ts_deque));
std::thread t2(thread_function, std::ref(ts_deque));
t1.join();
t2.join();
ts_deque.print();
return 0;
}
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?