【问题标题】:returning variables from a thread process function in Python 3从 Python 3 中的线程处理函数返回变量
【发布时间】:2014-09-05 10:21:41
【问题描述】:

我正在处理一个更新主进程变量的线程。由于我没有成功传递参数,我不得不使用 global.但我不喜欢它,它不安全。不使用全局有什么办法吗?

我可以传递参数,但我的问题在于返回的对象。

我的代码:

#!usr/bin/python3
# -*- coding: UTF-8 -*-

import threading
import time

my_check = " CHECK "    # TODO replace with initial source data.

class MiThread(threading.Thread):   
    def __init__(self):
        threading.Thread.__init__(self)

    def run(self):  
        time.sleep(5)
        print("I'm the SECOND thread")
        global my_check
        my_check = " CHECK DONE!!!" # TODO replace with the updated source data.
        self.run()

print ("I'm the principal thread.")

t = MiThread()     
t.start()       
#t.join(1)        

while True:
    time.sleep(0.5)
    print("I'm the principal thread, too." + my_check)

这只是一个概念证明,我真的想在 tkinter 标签中编写一个小股票行情显示器,我需要至少两个线程:更新线程(用于更新要显示的信息)和显示线程(它必须每 0.3 秒更改一次标签的文本)。

【问题讨论】:

    标签: python multithreading python-3.x arguments return


    【解决方案1】:

    您可以将线程执行的结果存储在线程对象的实例变量中:

    import threading
    import time
    
    class MiThread(threading.Thread):   
        def __init__(self):
            self.my_check = " CHECK "
            threading.Thread.__init__(self)
    
        def run(self):  
            time.sleep(5)
            print("I'm the SECOND thread")
            self.my_check = " CHECK DONE!!!"
    
    print ("I'm the principal thread.")
    
    t = MiThread()     
    t.start()         
    
    while True:
        time.sleep(0.5)
        print("I'm the principal thread, too." + t.my_check)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-12
      • 2023-03-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多