Python线程死锁

标签 python multithreading deadlock

我有两个线程(生产者和消费者),我与 Queue 共享数据。问题是,当我强行中止生产者时,消费者有时会锁定。

我在文档中读到取消带有队列的线程可能会破坏队列并导致死锁。我没有明确获取任何锁,但阅读 Queue.py 的源代码说 putget 正在这样做。

拜托,有谁知道当我中止线程时,它可能在 get/put 的中间,即使用锁然后不释放它?我该怎么办?有时我需要提前终止生产者。使用进程而不是线程会有什么不同吗?

最佳答案

也许这会有所帮助:

import threading

class MyQueue:
    def __init__(self):
        self.tasks = []
        self.tlock = threading.Semaphore(0)
        self.dlock = threading.Lock()
        self.aborted = False

    def put(self, arg):
        try:
            self.dlock.acquire()
            self.tasks.append(arg)
        finally:
            self.dlock.release()
            self.tlock.release()

    def get(self):
        if self.aborted:
            return None
        self.tlock.acquire()
        if self.aborted:
            self.tlock.release()
            return None
        try:
            self.dlock.acquire()
            if self.tasks:
                return self.tasks.pop()
            else: # executed abort
                return None
        finally:
            self.dlock.release()

    def abort(self):
        self.aborted = True
        self.tlock.release()

# TESTING

mq = MyQueue()
import sys

def tlog(line):
    sys.stdout.write("[ %s ] %s\n" % (threading.currentThread().name, line))
    sys.stdout.flush()

def reader():
    arg = 1
    while arg is not None:
        tlog("start reading")
        arg = mq.get()
        tlog("read: %s" % arg)
    tlog("END")

import time, random
def writer():
    try:
        pos = 1
        while not mq.aborted:
            x = random.random() * 5
            tlog("writer sleep (%s)" % x)
            pending = x
            while pending > 0:
                tosleep = min(0.5, pending)
                if mq.aborted:
                    return
                time.sleep(tosleep)
                pending -= tosleep

            tlog("write: %s" % x)
            mq.put("POS %s  val=%s" % (pos, x))
            pos += 1
    finally:
        tlog("writer END")

def testStart():
    try:
        for i in xrange(9):
            th = threading.Thread(None, reader, "reader %s" % i, (), {}, None)
            th.start()
        for i in xrange(3):
            th = threading.Thread(None, writer, "writer %s" % i, (), {}, None)
            th.start()
        time.sleep(30) # seconds for testing
    finally:
        print "main thread: abort()"
        mq.abort()

if __name__ == "__main__":
    testStart()

关于Python线程死锁,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10760948/

相关文章:

c# - Windows Phone HttpClient PostAsync 挂起且无响应

linux - 如何解决SMP中的spinlock锁定,irq和function都需要锁?

python - 填充 Pandas Dataframe 中的货币缺失数据

python - 将 Distutils 用于纯模块有什么意义?

C++ 11线程初始化与成员函数编译错误

c# - 异步调用是需要在当前进程中多出一个线程还是使用线程池中的另一个线程?

c# - 同步等待异步方法在同一线程上完成

python - win32api.GetUserNameEx() 转换为 .exe 时不起作用

python - 带组但不带值字段的数据透视表

python - 同时输出到终端时保持用户输入的完整性