which is better or faster, A or B?
std::deque<Myclass> queue;
... // do something
std::size_t size = 0;
... // create n threads, one push queue and others pop queue.
// a thread do below
#ifdef A
pthread_rwlock_wrlock(&rwlock);
queue.push_front(myobj);
size = queue.size();
pthread_rwlock_unlock(&rwlock);
#endif
#ifdef B
pthread_rwlock_wrlock(&rwlock);
queue.push_front(myobj);
pthread_rwlock_unlock(&rwlock);
// if there is some operation,
// I think this B is better,
// because I should get the newest size.
pthread_rwlock_rdlock(&rwlock);
size = queue.size();
pthread_rwlock_unlock(&rwlock);
#endif
// other threads do below
pthread_rwlock_wrlock(&rwlock);
queue.pop_back();
pthread_rwlock_unlock(&rwlock);
That’s my not understanding.
Any information or suggestion is great help for me!
Apologize for my poor English!
Your A version is faster as you need to acquire the lock only once (you need to acquire the write lock once at any rate). Also, the returned size will be the latest (at the time of push) as no other thread can access the queue at the same time.
If you do B, you might get a different answer for size (as you noted), however, once you release the lock (in either scenarios) the
sizevariable can always hold stale value (a thread might have updated the queue by the time you want to use the value insize)Also, the readers should query the queue for its size (within the protected section) to avoid an exception if the queue is empty