gpt4 book ai didi

python - 从Python 3中的线程处理函数返回变量

转载 作者:太空宇宙 更新时间:2023-11-03 18:17:35 25 4
gpt4 key购买 nike

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

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

我的代码:

#!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 秒更改一次标签文本)。

最佳答案

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

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)

关于python - 从Python 3中的线程处理函数返回变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24754528/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com