0

How can I protect the vector v from crashing? And another question, why is not it already crashed, shouldn't it?

#include <Windows.h> #include <thread> #include <vector> #include <algorithm> #include <iostream> using namespace std; vector<int> v; void a() { while (true) { v.push_back(1); Sleep(100); } } void b() { while (true) { if (!v.empty()) { v.erase(v.begin()); } Sleep(100); } } void c() { while (true) { v.push_back(1); Sleep(100); } } int main() { thread(&a).detach(); thread(&b).detach(); thread(&c).detach(); while (true) { for (int i = 0; i < v.size(); i++) { v[i]++; } cout << v.size() << endl; if (!v.empty()) v.erase(v.begin()); Sleep(100); } } 
3
  • 4
    A mutex? Commented Jan 8, 2013 at 9:22
  • possible duplicate: stackoverflow.com/questions/12260946/… Commented Jan 8, 2013 at 9:27
  • Just to add to what others said, if you are only reading contents of a vector from multiple threads, it is thread-safe. Commented Jan 8, 2013 at 10:05

2 Answers 2

1

To access one vector from multiple thread, you need to add std::mutex, idiomatic way is to implement RAII, see below demo code:

#include <mutex> #include <thread> class raii_vector { public: raii_vector() { } void Add() { std::lock_guard<std::mutex> lock(m_); v_.push_back(1); } void Remove() { std::lock_guard<std::mutex> lock(m_); if (!v_.empty()) { v_.erase(v_.begin()); } } private: std::mutex m_; std::vector<int> v_; }; raii_vector rv; void a() { while (true) { rv.Add(); std::cout << "adding " << std::endl; std::chrono::milliseconds dura( 100 ); std::this_thread::sleep_for( dura ); } } void b() { while (true) { std::cout << "removing " << std::endl; rv.Remove(); std::chrono::milliseconds dura( 100 ); std::this_thread::sleep_for( dura ); } } int main(int argc, char* argv[]) { std::thread t1(a); std::thread t2(b); t1.join(); t2.join(); return 0; } 
Sign up to request clarification or add additional context in comments.

Comments

0

When wanting to use data structures such as vectors from multiple threads, I've found the Intel Threading Building Blocks library to be really useful.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.