Skip to content

Instantly share code, notes, and snippets.

@ph87
Created May 31, 2017 10:07
Show Gist options
  • Save ph87/d07e6cd8583cb47aa822b58cda321d98 to your computer and use it in GitHub Desktop.
Save ph87/d07e6cd8583cb47aa822b58cda321d98 to your computer and use it in GitHub Desktop.
死锁示例
#!/usr/bin/env python
# encoding: utf-8
import time
def multi_acquire_worker(mutex):
''' 同一线程多次请求同一资源,直接造成死锁
为了解决在同一线程中多次请求同一资源,使用可重入锁 threading.RLock
RLock 中维护着一个 Lock 和一个 counter,counter 记录了被 acquire 的
总次数,直到该线程中所有的 acquire 都被 release,其它的线程才能够获
得资源
>>> import threading
>>> mutex = threading.Lock()
>>> # mutex = threading.RLock()
>>> for i in range(10):
... thread = threading.Thread(
... target=multi_acquire_worker,
... args=(mutex,)
... )
... thread.start()
'''
mutex.acquire()
mutex.acquire()
mutex.release()
mutex.release()
def cross_acquire_worker(mutex_1, mutex_2):
'''
相互调用导致死锁
>>> import threading
>>> mutex_a = threading.Lock()
>>> mutex_b = threading.Lock()
>>> for args in [(mutex_a, mutex_b), (mutex_b, mutex_a)]:
... thread = threading.Thread(target=cross_acquire_worker, args=args)
... thread.start()
'''
mutex_1.acquire()
time.sleep(1)
mutex_2.acquire()
mutex_2.release()
mutex_1.release()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment