简体   繁体   中英

Trying to understand deadlocks in c

I'm studying for my systems programming examination, but am having some trouble coming up with a simple deadlock example in c. I understand deadlocks occur whenever the waiting process is still holding on to another resource that the first needs, however I am having a difficult time understanding it in terms of c code. Are there any simple examples someone can provide?

Are there any simple examples someone can provide?

Here is a simple example: a piece of code might need to acquire two locks, A and B, eg so it can atomically modify two pieces of data, one protected by A and the other by B. For example:

pthread_mutex_t a, b;

pthread_mutex_lock(&a);
pthread_mutex_lock(&b);
// ... process data protected by A and B
pthread_mutex_unlock(&b);
pthread_mutex_unlock(&a);

At the same time, another piece of code can have the same requirement, but merely acquire the locks in the opposite order:

pthread_mutex_lock(&b);
pthread_mutex_lock(&a);
// ... process data protected by A and B
pthread_mutex_unlock(&a);
pthread_mutex_unlock(&b);

In isolation, either approach works just fine. But when the two pieces of code execute concurrently, the following can occur:

// neither lock is held

// thread 1                      // thread 2
pthread_mutex_lock(&a);          pthread_mutex_lock(&b);
// thread 1 now holds A          // thread 2 now holds B
// thread 1 is waiting for B     // thread 2 is waiting for A
pthread_mutex_lock(&b);          pthread_mutex_lock(&a);

The last line constitutes a deadlock : thread 1 is blocked waiting for lock B, which is held by thread 2. Thread 2 is blocked waiting for lock A, which is held by thread 1. As written, the threads are blocked indefinitely and neither can proceed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM