views:

145

answers:

2

I am writing a multi-threaded program using OpenMP in C++. At one point my program forks into many threads, each of which need to add "jobs" to some container that keeps track of all added jobs. Each job can just be a pointer to some object.

Basically, I just need the add pointers to some container from several threads at the same time.

Is there a simple solution that performs well? After some googling, I found that STL containers are not thread-safe. Some stackoverflow threads address this question, but none that forms a consensus on a simple solution.

+7  A: 

There's no built-in way to do this. You can simply use a lock to guard one of the existing container types. It might be a better idea to have each thread use it's own container, then combine the results together in the end.

Billy ONeal
+1  A: 

Using a mutex or similar synchronization primitive to control access to a linked list is not very difficult, so I'd recommend you try that first.

If it performs so poorly that you can't use it, try this instead: give each thread its own job queue, and have the job consumer check all the queues in turn. This way each queue has only one reader and one writer, so a lock-free implementation is relatively straightforward. By this I mean it may exist for your platform; you should not attempt to write it yourself.

David Seiler