using a stack container with threads

B

Brad Tilley

I was wondering if anyone has tried using std::stack with threads? I
have a threaded application that uses a std::queue right now and I had
a need to insert jobs at the front of the queue. So naturally, I
thought a stack was perfect for that, but have never used a stack to
feed threads Just thought I'd ask here.

Thanks,

Brad
 
A

Anthony Williams

Brad Tilley said:
I was wondering if anyone has tried using std::stack with threads? I
have a threaded application that uses a std::queue right now and I had
a need to insert jobs at the front of the queue. So naturally, I
thought a stack was perfect for that, but have never used a stack to
feed threads Just thought I'd ask here.

std::stack works fine with threads, provided you ensure that you
associate it with a mutex, and lock the mutex before each full operation
(and release it afterwards).

I say "full operation" above because popping requires more than one
member function call --- s.empty()/s.size() to check whether there is an
item, s.top() to get the value and s.pop() to remove it from the
stack. If multiple threads are removing items then you need to hold the
mutex across all 3 calls in the pop operation, otherwise you can end up
with a nasty race condition.

Anthony
 
B

Brad Tilley

std::stack works fine with threads, provided you ensure that you
associate it with a mutex, and lock the mutex before each full operation
(and release it afterwards).

I say "full operation" above because popping requires more than one
member function call --- s.empty()/s.size() to check whether there is an
item, s.top() to get the value and s.pop() to remove it from the
stack. If multiple threads are removing items then you need to hold the
mutex across all 3 calls in the pop operation, otherwise you can end up
with a nasty race condition.

Anthony

Thanks. I use boost threads and do scope level mutex locking. So I
think I've addressed that issue. I appreciate the advice, I'll switch
the container to std::stack and see how it goes.

Brad
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,145
Messages
2,570,824
Members
47,370
Latest member
desertedtyro29

Latest Threads

Top