lichgo
lichgo

Reputation: 533

How to stop a blocking pthread_join() implemented in a shared library

My code is calling a function from a third-party library before the exit of the program. Unfortunately the called function blocks the main thread, which is caused by pthread_join() in the .so library.

Since it is inside the library, which is out of my control, I am wandering how to break it so the main thread can proceed.

Attaching the info from using gdb:

0x00007ffff63cd06d in pthread_join (threadid=140737189869312, thread_return=0x0)
    at pthread_join.c:89
89          lll_wait_tid (pd->tid);
Missing separate debuginfos, use: debuginfo-install keyutils-libs-1.4-5.el6.x86_64 krb5-libs-1.10.3-65.el6.x86_64 libcom_err-1.41.12-23.el6.x86_64 libselinux-2.0.94-7.el6.x86_64 openssl-1.0.1e-57.el6.x86_64

Thanks in advance.

Upvotes: 1

Views: 455

Answers (2)

Florian Weimer
Florian Weimer

Reputation: 33717

If you call exit, the process is terminated without shutting down the other threads.

If you have a pthread_t handle for the thread that is being waited on, you can perhaps call pthread_cancel on it, but if the application and libraries are not prepared to handle thread cancellation, it will cause other problems. (Canceling the thread does pthread_join will not help because the shutdown will then block on the same thread that pthread_join waits on.)

In general, it is probably a better idea to figure out why the pthread_join call is waiting indefinitely in your environment (that is, why the other thread is not termining), and fix that.

Upvotes: 1

David Schwartz
David Schwartz

Reputation: 182819

The library is designed to have the calling thread wait for something to finish. Since you can't change the design of the library, just call the library from a thread that has nothing else to do.

By the way you design the interaction, you can then get whatever semantics you want. If you want the calling thread to get the results at its convenience later, you can use a promise/future. You can design the calling thread to wait a certain amount of time and then timeout. In the timeout case, you can ignore the result if you don't need it or you can design some way to check and get the result later. You can also have the thread that calls the library do whatever needs to be done with the result so that the calling thread doesn't have to worry about it.

Just quarantine the code you can't control and write whatever code around it you need to get the behavior your code needs. The library needs the thread that calls it to wait until it's done, so isolate the thread that calls it and let the library have what it wants.

Upvotes: 2

Related Questions