5.6 dead Lock
(1) deadlock : Two threads attempt to occupy two resources at the same time, and lock the corresponding shared resources in different order.
(2) Solution:
① Scenario 1: Lock the appropriate shared resources in the same order
② Scenario 2: Use Pthread_mutex_trylock (), which is a non-blocking version of the Pthread_mutex_lock () function.
"Programming Experiment" deadlock
Dead_lock.c
#include <pthread.h>#include<errno.h>#include<string.h>#include<stdio.h>#include<stdlib.h>typedefstruct{ intvalue; pthread_mutex_t Mutex;} Resourcea;typedefstruct{ intvalue; pthread_mutex_t Mutex;} Resourceb;typedefstruct{Resourcea*RA; Resourceb*RB;} Storage;void* A_FN (void*Arg) {Storage* s = (storage*) Arg; //first to Resourcea lockingPthread_mutex_lock (&s->ra->mutex); Sleep (1); printf ("0X%LX is waiting for resourceb...\n", Pthread_self ()); //again RESOURCEB lockingPthread_mutex_lock (&s->rb->mutex); printf ("resourcea value is:%d\n", s->ra->value); printf ("Resourceb value is:%d\n", s->rb->value); Pthread_mutex_unlock (&s->rb->mutex); Pthread_mutex_unlock (&s->ra->mutex); return(void*)0;}void* B_FN (void*Arg) { /*deadlock storage* s = (storage*) arg; First to RESOURCEB locking Pthread_mutex_lock (&s->rb->mutex); Sleep (1); printf ("0x%lx is waiting for resourcea...\n", Pthread_self ()); Again resourcea locking Pthread_mutex_lock (&s->ra->mutex); printf ("Resourcea value is:%d\n", s->ra->value); printf ("Resourceb value is:%d\n", s->rb->value); Pthread_mutex_unlock (&s->ra->mutex); Pthread_mutex_unlock (&s->rb->mutex); */ //Solution: Lock in the same order as a threadstorage* s = (storage*) Arg; //first to Resourcea lockingPthread_mutex_lock (&s->ra->mutex); Sleep (1); printf ("0X%LX is waiting for resourceb...\n", Pthread_self ()); //again RESOURCEB lockingPthread_mutex_lock (&s->rb->mutex); printf ("resourcea value is:%d\n", s->ra->value); printf ("Resourceb value is:%d\n", s->rb->value); Pthread_mutex_unlock (&s->rb->mutex); Pthread_mutex_unlock (&s->ra->mutex); return(void*)0;}intMainvoid) {Resourcea ra; Resourceb RB; Ra.value= -; Rb.value= $; Pthread_mutex_init (&Ra.mutex, NULL); Pthread_mutex_init (&Rb.mutex, NULL); Storage s= {&ra, &RB}; intErr =0; pthread_t thread_a, Thread_b; if(Err = Pthread_create (&thread_a, NULL, A_FN, (void*) &s)! =0) {fprintf (stderr,"pthread_create:%s\n", Strerror (errno)); Exit (1); } if(Err = Pthread_create (&thread_b, NULL, B_FN, (void*) &s)! =0) {fprintf (stderr,"pthread_create:%s\n", Strerror (errno)); Exit (1); } pthread_join (Thread_a, NULL); Pthread_join (Thread_b, NULL); Pthread_mutex_destroy (&Ra.mutex); Pthread_mutex_destroy (&Rb.mutex); return 0;}/*0xb6d08b70 is waiting for resourceb ... Resourcea value is:100 RESOURCEB value is:200//deadlock, stop at this location 0xb7709b70 is waiting for resourceb ... Resourcea value is:100 RESOURCEB value is:200//output here when no deadlock occurs*/
9th thread Programming (8) _ Deadlock