Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/340.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/multithreading/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python wx.StaticText是线程安全的吗?_Python_Multithreading_Thread Safety_Wxpython - Fatal编程技术网

Python wx.StaticText是线程安全的吗?

Python wx.StaticText是线程安全的吗?,python,multithreading,thread-safety,wxpython,Python,Multithreading,Thread Safety,Wxpython,例如,我使用wx.StaticText对象作为计数器,它是线程安全的吗?例如: class TaskFrame(wx.Frame): def __init__(self): self.Counter = wx.StaticText(MainPanel, id = -1, label = "0") 如果同时在不同线程中为self.Counter设置GetLabel和SetLabel,会发生什么情况?我会有麻烦吗 Result = self.Counter.GetLabel

例如,我使用
wx.StaticText
对象作为计数器,它是线程安全的吗?例如:

class TaskFrame(wx.Frame):
    def __init__(self):
        self.Counter = wx.StaticText(MainPanel, id = -1, label = "0")
如果同时在不同线程中为
self.Counter
设置
GetLabel
SetLabel
,会发生什么情况?我会有麻烦吗

Result = self.Counter.GetLabel()
self.Counter.SetLabel(WhateverResult)

它不是线程安全的。引用这句绝妙的话:

在wxPython世界中,有三种相关的“线程安全”方法。如果在更新用户界面时不使用这三个选项中的一个,则可能会遇到奇怪的问题。有时您的GUI会工作得很好。其他时候,它会毫无理由地使Python崩溃。因此需要线程安全方法:wx.PostEvent、wx.CallAfter和wx.CallLater

简而言之,您可以在发布对象上创建接收器:

from wx.lib.pubsub import Publisher
Publisher().subscribe(update_function, 'update') # Params: callback, event name
然后从线程开始,使用:

尽管如此,如果您只想在进程之间共享变量,请使用。目前,您正在滥用GUI工具包来保存变量,而您应该使用内置类型来保存变量。正确地共享这些,并使用GUI显示数据

# Will trigger 'update_function' with argument 'My message'
wx.CallAfter(Publisher().sendMessage, 'update', 'My message')