one thread try to read from vector and another thread try to delete from vector how to do it

ZlapX commented: Sucks balls +0

Recommended Answers

All 2 Replies

Use a mutex to protect the access to vector. Mutexes are your best friends in multi-threading. A mutex (short for "mutual exclusion") is a thing that is supported by all multi-threading-capable operating systems (the API functions to use may change depending on your OS). What it does is that it allows one thread to lock the mutex while it's accessing memory in vector (read or write or both, doesn't matter). While the mutex is locked to one thread, it cannot be locked by another until it is released (or unlocked) by the thread that owns the lock. So if a thread wants to access the vector while another thread has a lock on it, it will be blocked (suspended execution) until the mutex is released and then it will lock it for itself and do its own operations on the vector. In code, using boost::thread library (which I recommend for that purpose, but others are similar):

vector<int> v; //say you have a global vector v of integers.
boost::mutex v_mutex; //create a global mutex for it.

int getValue_ThreadSafe(int Index) {
  //lock the mutex at first, if already locked, this will suspend execution until it's available.
  boost::unique_lock< boost::mutex > lock_access_here(v_mutex);
  //return the value and "lock_access_here" variable will go out of scope and release the lock on the mutex.
  return v[Index];
};

void push_back_ThreadSafe(int NewValue) {
  //Again same procedure..
  boost::unique_lock< boost::mutex > lock_access_here(v_mutex);
  //push_back, return and thus, release mutex lock.
  v.push_back(NewValue);
};

Other mutex implementation beside boost::thread exist of course, but this one is the most convenient, and the logic is the same for any other implementation of mutexes.

one thread try to read from vector and another thread try to delete from vector how to do it

As a forum policy we do not give code on a platter. If you want help, show some effort, post what you have tried and people will try and guide you.

commented: sucks balls +0
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.