I have recently encountered such a situation in multi-threaded programming. There are some variables in the program to be globally effective, and multiple threads are accessible. Since there is no consideration, there are some problems with threads. So, I thought of the mutex, but I encountered more serious situations: some threads will be killed by their parent threads for a while. If it has implemented the lockover operation of the mutually exclusive lock and unlocked If it causes the deadlock, it causes the program to frequently errors. This is indeed a confusing issue, how to make the lock to unknown to the lock after the thread is killed. Fortunately, the unlocking of threads is performed by a function, and the entrance to the function is locked, and the exit is unlocked. So, the spirit is flashed, why don't I declare a class, the class instance declares the mutex lock at the entrance, unlocking the exit. Ha, in order to ensure lock, unlocking must be paired, why do we have used the constructor and destructive functions of C . If I don't declare this class instance, but directly assign memory in the stack, all in the function exit, which will be destructed. Please see: TLOCK Terminal file: #ifndef _tlock_ # define _tlock _ // debug output macro #define _my_test_ # undef _MY_TEST _ // Name: Auto lock, unlock class TLOCK // function: to multi-threaded, unlock function // usage: Do not adopt new ways to declare an instance, otherwise automatic locking and unlocking function will fail #include
TLOCK class implementation file:
#include "tlock.hpp" // Declare the TLOCK class instance in the function, you can ensure that the function is automatically unlocked // TLOCK constructor TLOCK :: TLOCK (pthread_mutex_t * lock) {#ifDef _my_test_ cout << "Begin to Lock Mutex ..." << Endl; #ndif #ifdef debug log.write (log_dev | Trival | log_time_tid, "thread lock operation ... / n"); #ndif mylock = lock; pthread_mutex_lock (Mylock ); // lock operation} // TLOCK destructor Tlock :: ~ Tlock () {#ifdef _my_test_ cout << "begin to unlock mutex ..." << endl; #ndif #ifdef debug log.write LOG_DEV | Trival | log_time_tid, "thread unlock operation ... / n"); #ndif pthread_mutex_unlock (mylock); // unlock operation}
Everyone understands it, it is actually very simple. I am addicted in the function you need to add: int myfunc (int index) {TLOCK LOCK (& LockMuteX); // ...} Key here: Tlock Lock (& Lockmutex); Constructor MP (mutual) The pointer to the pointer is passed in automatically lock, and then the system will automatically clear the TLOCK instance Lock when the function myfunc exits because it is declared on the stack. As a class, the corrective function function will be debuted in time, so our lovely mutually exclusive locks have to be unlocked ^ _ ^
Later, the modified add-on-lock operation performance seems to be not bad, the program is stable. If you have also encountered a similar problem, try this usage.