Python多线程同步

Posted bongem

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Python多线程同步相关的知识,希望对你有一定的参考价值。

对Python多线程实现同步机制及其遇到的一些问题。本文给出了样例代码 ,主要包括Condition,Event and Queue三种机制

1. 锁机制

threading的Lock类,用该类的acquire函数进行加锁,用realease函数进行解锁,当一个线程调用锁的acquire()方法获得锁时,锁就进入“locked”状态。每次只有一个线程可以获得锁。如果此时另一个线程试图获得这个锁,该线程就会变为“blocked”状态,称为“同步阻塞”

在此没有给出样例后面条件

 

2.条件 Contidion

代码段:

class Reader(threading.Thread):

    def __init__(self, condition, data):

        threading.Thread.__init__(self)

        self.condition = condition

        self.data = data

        pass

 

    def run(self):

        while True:

            with self.condition:

                print("waiting...")

                self.condition.wait()

                msg = self.data.pop()

                if "exit" == str(msg).lower():

                    print ("exit")

                    break

                print("read date:{}".format(msg))

 

def test_condition():

    condition = threading.Condition()

    dl=[]

 

    reader = Reader(condition, dl)

    reader.daemon = True

    reader.start()

 

    while True:

        with condition:

            msg = input("输入:")

            dl.append(msg)

            print("notify...")

            condition.notifyAll()

            if "exit" == msg.lower():

                break

        time.sleep(0.012)

 

2.事件 Event

代码段:

class Reader2(threading.Thread):
    def __init__(self, event, data):
        threading.Thread.__init__(self)
        self.event = event 
        self.data = data
        pass

    def run(self):
        while True:
            print("waiting...")
            self.event.wait()
            msg = self.data.pop()
            if "exit" == str(msg).lower():
                print ("exit")
                break
            print("read date:{}".format(msg))

def test_event():
    event = threading.Event()
    dl=[]

    reader2 = Reader2(event, dl)
    reader2.daemon = True
    reader2.start()

    while True:
        msg = input("输入:")
        dl.append(msg)
        print("notify...")
        event.set()
        event.clear()

        if "exit" == msg.lower():
            break
        time.sleep(0.012)
    pass
 

2.队列 Queue

代码段:

class Reader3(threading.Thread):
    def __init__(self, queue):
        threading.Thread.__init__(self)
        self.queue = queue
    
    def run(self):
        while True:
            print("waiting...")
            msg = self.queue.get()
            print("read data: {}".format(msg))
            if "exit" == msg.lower():
                break
            self.queue.task_done()
        pass

def test_queue():
    q = queue.Queue()

    reader3 = Reader3(q)
    reader3.daemon = True
    reader3.start()

    while True:
        msg = input("输入:")
        q.put(msg)
        print("notify...")
        time.sleep(0.01)
        if "exit" == msg.lower():
            break
    pass

参考文档:https://zhuanlan.zhihu.com/p/27963810

以上是关于Python多线程同步的主要内容,如果未能解决你的问题,请参考以下文章

Python 多线程同步队列模型

Python多线程同步LockRLockSemaphore

python 多进程/多线程/协程 同步异步

Python之多线程:线程互斥与线程同步

python多线程同步机制Semaphore

python多线程同步机制Lock