开发者

Simple C++ container class that is thread-safe for writing

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 s开发者_C百科olution.


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜