Sunday, August 31, 2014

[Explained] pthread_mutex_destroy failed


If you ever run into the following error while running a multithreaded application in C++ application which makes use of mutex's for synchronization



networkDataShareSyncApp: /usr/local/include/boost/thread/pthread/mutex.hpp:47: 
boost::mutex::~mutex(): Assertion `!pthread_mutex_destroy(&m)' failed.
Aborted (core dumped)


gdb detailed stack trace for the same problem:

(gdb) bt
#0  0x00000034594328a5 in raise () from /lib64/libc.so.6
#1  0x0000003459434085 in abort () from /lib64/libc.so.6
#2  0x000000345942ba1e in __assert_fail_base () from /lib64/libc.so.6
#3  0x000000345942bae0 in __assert_fail () from /lib64/libc.so.6
#4  0x0000000000404391 in boost::mutex::~mutex (this=0x608e80, 
__in_chrg=<value optimized out>) at 
/usr/local/include/boost/thread/pthread/mutex.hpp:47
#5  0x0000003459435da2 in exit () from /lib64/libc.so.6
#6  0x000000345941ece4 in __libc_start_main () from /lib64/libc.so.6
#7  0x00000000004036a9 in _start ()
(gdb) 


Then the problem might be:
a) Either your main() thread/program is exiting without joining the threads, and one of the threads is still using/referencing to the mutex variable
b) You are trying to destroy/delete the mutex explicitly from one of your thread, while it is still being referenced/used from another thread. Attempting to destroy a locked mutex results in undefined behavior.

Source : https://linux.die.net/man/3/pthread_mutex_destroy.
Read more about an interesting discussion here.


No comments:

Interview Question Preperation : Find longest subarray whose sum is equal to K

Software Engineering Practice interview question Given a array of N elements. Find the length of Longest Subarray whose sum is equal to give...