python中intvar_在Python线程中使用Intvar/DoubleVar是否安全?

基于_tkinter模块的comments in the source code,看起来tkinter实际上至少是为了使线程安全,只要Tcl是用enable-threads选项构建的。这是由Python跟踪器(issue11077)上的一个已解决的错误所支持的,它指出tkinter不是线程安全的,最终确定与tkinter有关的所有线程安全问题都是在python2.7.3+中修复的bug

以下是_tkinter模块的消息来源对此问题的看法:The Tcl interpreter is only valid in the thread that created it, and all Tk activity must happen in this thread, also. That means that the mainloop must be invoked in the thread that created the interpreter. Invoking commands from other threads is possible; _tkinter will queue an event for the interpreter thread, which will then execute the command and pass back the result. If the main thread is not in the mainloop, and invoking commands causes an exception; if the main loop is running but not processing events, the command invocation will block.

因此,只要主循环在应用程序的主线程中处于活动状态,tkinter就会自动安排方法在主线程中运行,这将使它成为线程安全的。也就是说,除了实际的Tkinter源代码和上面的bug报告之外,互联网上的大多数源代码都表明使用Tkinter线程会导致崩溃。我不太确定该相信什么,尽管在一些小例子中,从线程更新GUI效果很好。在

现在,您特别想知道与Tk小部件相关的线程安全规则是否也适用于Variable子类。确实如此:以下是Variable的一些实现,IntVar的父元素:class Variable:

_default = ""

_tk = None

def __init__(self, master=None, value=None, name=None):

"""Construct a variable

MASTER can be given as master widget.

VALUE is an optional value (defaults to "")

NAME is an optional Tcl name (defaults to PY_VARnum).

If NAME matches an existing variable and VALUE is omitted

then the existing value is retained.

"""

# ...snip...

if not master:

master = _default_root

self._master = master

self._tk = master.tk

def set(self, value):

"""Set the variable to VALUE."""

return self._tk.globalsetvar(self._name, value)

当您set一个变量时,它调用与Variable关联的主小部件上的globalsetvar方法。_tk.globalsetvar方法is implemented in C,并内部调用var_invoke,后者内部调用WaitForMainLoop,后者将尝试调度在主线程中执行的命令,如上面我所包含的_tkinter源中的引用所述。在

^{pr2}$

请注意,此代码路径也用于get操作,因此set和{}操作都由相同的规则管理。在

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值