pthreads - c++ correct use of mutex -


i have multithreaded project , i've run through valgrind --tool=helgrind , showed me few errors. i'm using mutex there exaxtly how found on net how use it, can please show me whats wrong?

#include <iostream> #include <pthread.h>  #define max_threads     100 #define max_sessions    100  static pthread_mutex_t  m_create_session_lock= pthread_mutex_initializer;   .....    void connection::proccess(threadvarstype &thread) {     ....      pthread_mutex_lock(&m_create_session_lock);      unsigned int ii;     (ii=0; ii<max_sessions; ii++) {         if (session[ii]==null) {             break;         }     }     if (ii==max_sessions-1) {         ....         pthread_mutex_unlock(&m_create_session_lock);                       // unlock session mutex         ....         return;     } else {         ....         pthread_mutex_unlock(&m_create_session_lock);                       // unlock session mutex         ....     }      .... } 

and error messages:

==4985== thread #1's call pthread_mutex_lock failed ==4985==    error code 22 (einval: invalid argument)     .... ==4985== thread #1 unlocked invalid lock @ 0x4e7b40 ==4985==    @ 0x32cd8: pthread_mutex_unlock (hg_intercepts.c:610)     .... ==4985== thread #1's call pthread_mutex_unlock failed ==4985==    error code 22 (einval: invalid argument)     .... ==4985== thread #1's call pthread_mutex_lock failed ==4985==    error code 22 (einval: invalid argument)     .... ==4985== thread #1 unlocked invalid lock @ 0x4e7b40 ==4985==    @ 0x32cd8: pthread_mutex_unlock (hg_intercepts.c:610)     .... ==4985== thread #1's call pthread_mutex_unlock failed ==4985==    error code 22 (einval: invalid argument) 

first, check return values of function calls. if pthread call fails, it's choice call abort() core-dump if have enabled or drop debugger if running one.

the pthread function calls should never fail, means wrong program. in c or c++ program commonly causes mysterious failures memory corruption. use valgrind in normal modes check that.

another thing can cause pthread calls fail not compile using -pthread. if using gcc should compile , link using gcc command gcc -pthread. link pthread library , set preprocessor defines may important system's header files.

some systems compile , link program using pthread calls without linking pthread libraries. done program or library can made thread-safe without using threads. thread calls linked dummy functions unless real pthread library linked. can lead function calls failing.

so make sure building correct compiler options include pthread libraries.

another possible cause if building on whacked-out half-and-half hybrid os started linux 2.4 , got upgraded linux 2.6 nptl @ point (i worked on once). if attempting compile against old header files outdated definition of pthread_mutex_initializer or wrong size type of pthread_mutex_t cause problem.


Comments