本文介绍了Python 线程:使线程函数从外部信号返回的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

谁能指出这段代码有什么问题.我试图通过一个变量标志返回线程,我想在我的主线程中控制它.

test27.py

导入线程导入时间锁 = threading.Lock()定义读取(x,y):标志 = 1为真:锁定.获取()尝试:z = x+y;w = x-y打印 z*w时间.睡眠(1)如果标志== 0:打印中止"返回最后:打印单线程执行"锁.释放()

test28.py

导入时间,线程从 test27 导入读取打印你好,欢迎"一 = 2;乙 = 5t = threading.Thread(target = Read, name = 'Example Thread', args = (a,b))t.start()时间.sleep(5)t.flag = 0 # 这不是更新 Read FUNCTION 中的标志变量t.join() # 由于上面的命令,我无法等到线程完成.它在阻塞.打印程序结束"
解决方案

Thread 类可以用 target 参数实例化.然后你只需给它一个应该在新线程中执行的函数.这是启动一个简单线程的便捷方式,但为了获得更多控制,通常更容易从 Thread 继承一个类,该类具有额外的成员变量,例如 flag中止.

例如:

导入时间进口螺纹类 MyThread(threading.Thread):def __init__(self, x, y):super().__init__()# 或在 Python 2 中:# super(MyThread, self).__init__()自我.x = x自我.y = yself._stop_requested = False定义运行(自我):而不是 self._stop_requested:z = self.x + self.yw = self.x - self.y打印 (z * w)时间.睡眠(1)定义停止(自我,超时=无):self._stop_requested = Trueself.join(超时)

然后,要启动线程,调用 start() 然后停止它调用 stop():

>>>def run_thread_for_5_seconds():... t = MyThread(3, 4)... t.start()... time.sleep(5)... t.stop()...>>>run_thread_for_5_seconds()-7-7-7-7-7>>>

Could anyone please point out whats wrong with this code. I am trying to return the thread through a variable flag, which I want to control in my main thread.

test27.py

import threading
import time

lock = threading.Lock()

def Read(x,y):
    flag = 1
    while True:
        lock.acquire()
        try:
            z = x+y; w = x-y
            print z*w
            time.sleep(1)
            if flag == 0:
                print "ABORTING"
                return
        finally:
            print " SINGLE run of thread executed"
            lock.release()

test28.py

import time, threading

from test27 import Read

print "Hello Welcome"
a = 2; b = 5
t = threading.Thread(target = Read, name = 'Example Thread', args = (a,b))
t.start()
time.sleep(5)
t.flag = 0 # This is not updating the flag variable in Read FUNCTION
t.join() # Because of the above command I am unable to wait until the thread finishes. It is blocking.
print "PROGRAM ENDED"
解决方案

The Thread class can be instantiated with the target argument. Then you just give it a function which should be executed in a new thread. It is a convenient way to start a simple thread, but for more control it is usually easier to have a class inherited from Thread, which has additional member variables, like the flag for aborting.

For example:

import time
import threading

class MyThread(threading.Thread):
    def __init__(self, x, y):
        super().__init__()
        # or in Python 2:
        # super(MyThread, self).__init__()
        self.x = x
        self.y = y
        self._stop_requested = False

    def run(self):
        while not self._stop_requested:
            z = self.x + self.y
            w = self.x - self.y
            print (z * w)
            time.sleep(1)

    def stop(self, timeout=None):
        self._stop_requested = True
        self.join(timeout)

Then, to start the thread, call start() and then to stop it call stop():

>>> def run_thread_for_5_seconds():
...     t = MyThread(3, 4)
...     t.start()
...     time.sleep(5)
...     t.stop()
...
>>> run_thread_for_5_seconds()
-7
-7
-7
-7
-7
>>>

这篇关于Python 线程:使线程函数从外部信号返回的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-05 07:26