non-thread safe libraries and threads

Go To StackoverFlow.com

0

Using non-thread safe libraries with threads. Say I have a library that makes a connection to a server. And it is non thread safe. Can I use initiate the library inside 2 threads?

ie:

thread_1(){
telnet_lib_t *connection1;

while(1){
do_somestuff
}

free_telnet(connection1);
}

thread_2(){
telnet_lib_t *connection2;

while(1){
     do_somestuff;
}

free_telnet(connection2);
}

Would this work? Now I have 2 independent instances of the library running. So they would not interfere with each other, right?

2012-04-04 01:26
by Craig Sparks
You can run it in two threads, but there is probably only one copy of the library on your machine. Meaning that the calls from either thread could cause problems for you - Hunter McMillen 2012-04-04 01:31


1

No, you can't do this. If the library has no global state and its functions are just internally non-thread-safe, you could solve the problem by having the whole library protected by a mutex and only allowing one thread to access it at once (but this might be prohibitive, especially if the library performs any slow or blocking tasks). But if the library fundamentally has a singular global state it uses, and no way to save/restore/swap states, then there's simply no way to use it in multiple threads (or even to use multiple contexts in alternation in a non-threaded program). Such libraries are generally considered trash and should be replaced.

2012-04-04 01:31
by R..


0

It depends on why it isn't threadsafe.

For example, if the library uses some static variable then that would still be shared between two threads.

So, generally this would be a bad idea. If something isn't threadsafe don't use it in threads, but, you could fork a child process and then use it, which is heavier than threads, but safer.

2012-04-04 01:31
by James Black


0

Without knowing more about the specifics of the non-thread-safe library, it's not possible to say it's safe to use as you suggest.

If the library has any global shared resource (e.g. a global variable), the two threads could well step on each other, overwriting that global variable in a manner not intended by the library writer.

The trouble is, no amount of testing can prove with certainty that you will not eventually trigger a conflict.

If you must use the library in parallel, the only safe way I can think of to do that is to use process isolation... create multiple child processes that each load an instance of the library.

2012-04-04 01:31
by Eric J.


0

You can do that only if you know that the telnet_lib_t and its methods don't work with any global state (i.e. they are not relying on global variables). If you know that the library's state is contained within itself, for sure then use it, otherwise don't do it. Even if you don't run into any issue during your testing, it won't mean there isn't a problem lurking somewhere.

2012-04-04 01:35
by Gangadhar
Ads