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?
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.