python中线程之间的数据通信

iuh*_*chi 6 python python-multithreading

我是 python 的新手,我对 python 中的线程知之甚少。这是我的示例代码。

import threading
from threading import Thread
import time

check = False

def func1():
    print ("funn1 started")
    while check:
        print ("got permission")

def func2():
    global check
    print ("func2 started")
    time.sleep(2)
    check = True
    time.sleep(2)
    check = False

if __name__ == '__main__':
    Thread(target = func1).start()
    Thread(target = func2).start()
Run Code Online (Sandbox Code Playgroud)

我想要的是看到“获得许可”作为输出。但是使用我当前的代码,它不会发生。我假设func1线程在func2check值更改为True.

我怎样才能func1活下去?我在互联网上进行了研究,但找不到解决方案。任何帮助,将不胜感激。先感谢您!

jdo*_*ner 5

这里的问题是 func1 在 while 循环中执行检查,发现它为 false,并终止。因此第一个线程完成时没有打印“获得许可”。

我不认为这种机制正是您所寻找的。我会选择使用这样的条件,

import threading
from threading import Thread
import time

check = threading.Condition()

def func1():
    print ("funn1 started")
    check.acquire()
    check.wait()
    print ("got permission")
    print ("funn1 finished")


def func2():
    print ("func2 started")
    check.acquire()
    time.sleep(2)
    check.notify()
    check.release()
    time.sleep(2)
    print ("func2 finished")

if __name__ == '__main__':
    Thread(target = func1).start()
    Thread(target = func2).start()
Run Code Online (Sandbox Code Playgroud)

这里条件变量在内部使用互斥体在线程之间进行通信;所以一次只有一个线程可以获取条件变量。第一个函数获取条件变量,然后释放它,但注册它将等待,直到通过条件变量收到通知。然后,第二个线程可以获取条件变量,并且当它完成需要做的事情时,它通知等待线程它可以继续。


小智 0

from threading import Thread
import time

check = False

def func1():
    print ("funn1 started")
    while True:
        if check:
            print ("got permission")
            break

def func2():
    global check
    print ("func2 started")
    time.sleep(2)
    check = True
    time.sleep(2)
    check = False

if __name__ == '__main__':
    Thread(target = func1).start()
    Thread(target = func2).start()
Run Code Online (Sandbox Code Playgroud)