[Disclaimer: All Rights Reserved. You are welcome to reprint it. Do not use it for commercial purposes. Contact Email: feixiaoxing @ 163.com]
Precautions for preventing deadlocks:
(1) Write MultithreadingProgramFirst, write the correct program and then port it to multiple threads.
(2) check whether the program you write forgets to release the lock when it jumps out.
(3) If your module may use a lock again, we recommend that you use a nested lock.
(4) For some locksCodeDo not temporarily re-compile. We recommend that you use the locks in the library or the locks you have written.
(5) If a business needs to obtain multiple locks, it must be ensured that the locks are obtained in a certain order; otherwise, a deadlock will occur.
(6) write a simple test case to verify whether there is a deadlock
(7) write a program to verify deadlocks and avoid deadlocks from the source.
First, define basic data structures and macros,
[CPP] View plaincopy
-
- Typedef Struct_ Lock_info
-
- {
- CharLockname [32];
-
- HandleHlock;
-
- } Lock_info:
-
-
- Typedef Struct_ Thread_lock
-
- {
-
- IntThreadid;
-
- Lock_info * plockinfo [32];
-
- } Thread_lock;
-
- # Define critical_section_type 1
-
- # Define mutex_lock_type 2
-
- # Define semaphore_lock_type 3
-
- # Define normal_lock_type 4
-
-
- # Define waitforsingleobject (a, B )\
- Waitforsingleobject_stub ((Void*) A, normal_lock_type)
-
-
- # Define entercriticalsection ()\
-
- Waitforsingleobject_stub ((Void*) A, critical_section_type)
-
-
- # Define releasemutex ()\
-
- Releaselock_stub ((Void*) A, mutex_lock_type ))
-
- # Define releasesemaphore (a, B, c )\
-
- Releaselock_stub ((Void*) A, semaphore_lock_type ))
-
-
- # Define leavecriticalsection ()\
-
- Releaselock_stub ((Void*) A, critical_section_type ))
Then, rewrite the lock application function,
[CPP] View plaincopy
- VoidWaitforsingleobject_stub (Void* Hlock,IntType)
-
- {
-
- /* Step 1 */
-
- Waitforsingleobject (hdbglock );
-
- /* Check if Lock Loops arounds threads */
-
- Releasemutex (hdbglock );
-
- /* Step 2 */
-
- If(Normal_lock_type = type)
-
- Waitforsingleobject ((Handle) Hlock, infinite );
-
- Else If(Critical_section_type = type)
-
- Entercriticalsection (lpcritical_section) hlock );
-
- Else
- Assert (0 );
-
-
- /* Step 3 */
-
- Waitforsingleobject (hdbglock );
-
- /* Add lock to specified threadid list */
-
- Releasemutex (hdbglock );
-
- }
Finally, you need to rewrite the lock release function.
[CPP] View plaincopy
- VoidReleaselock_stub (Void* Hlock,IntType)
-
- {
-
- /* Step 1 */
-
- Waitforsingleobject (hdbglock );
-
- /* Remove lock from specified threadid list */
-
- Releasemutex (hdbglock );
-
- /* Step 2 */
-
- If(Mutex_lock_type) = type)
-
- Releasemutex (Handle) Hlock );
-
- Else If(Semaphore_lock_type = type)
-
- Releasesemaphore ((Handle) Hlock, 1, null );
- Else If(Critical_section_type = type)
-
- Leavecriticalsection (lpcritical_section) hlock );
-
- Assert (0 );
-
- }