views:

78

answers:

2

I am using a third-party C++ library (OpenFst), which is not particularly designed to be thread-safe. It does have some unused Mutex classes in there, though.

Now I would like to call some functions from that library and run them in Boost threads. How can I do that? Do I just have to write additional Mutex classes?

In particular, some of my threads will use some data structures from that library until they find that another thread has produced updated copies of those structures. I'm new to threads and don't really know where to start ...

+5  A: 

The safest way is to ensure that only one thread calls into the third-party library at a time - that is, take a mutex around EVERY call to the library. Making it so that multiple threads can use the library at once, however, is going to be quite complex, and requires a good understanding of threadsafe design as well as the design of the library itself.

If you audit the library and find it has no global state at all (ie, manipulating one FST will never, ever, EVER, interact with the same data as another FST manipulation), then it may be safe to take mutexes on the level of individual FSTs. And if there are some methods that don't modify the FST structures at all, it may safe to run them in multiple threads, provided there are no writers to the same FST. However, this requires a careful audit of the OpenFST code. I would recommend working with the original OpenFST developers here; they should be able to help point out potential pitfalls and threading issues.

bdonlan
A: 

You don't want to block access to the entire library.

Instead, just use your head - if you have a data structure that can be updated during the lifetime of any thread, then synchronize access to that datastructure.

If it's created before any thread starts executing and is used read-only, then no synchronizing needs to be done.

Larry Watanabe