wx中实现了3个线程安全的函数。如果在线程中,直接访问并更新主线程的UI,会遇到问题,有时候阻塞UI或者更新不起作用,有时严重的话会引起python崩溃。

三个安全线程如下:

  • wx.PostEvent
  • wx.CallAfter
  • wx.CallLater

其中,wx.CallLater是最抽象的线程安全函数,其次是callAfter,最后是PostEvent。

PostEvent用法:

import time
from threading import *
import wx # Button definitions
ID_START = wx.NewId()
ID_STOP = wx.NewId() # Define notification event for thread completion
EVT_RESULT_ID = wx.NewId() def EVT_RESULT(win, func):
"""Define Result Event."""
win.Connect(-1, -1, EVT_RESULT_ID, func) class ResultEvent(wx.PyEvent):
"""Simple event to carry arbitrary result data."""
def __init__(self, data):
"""Init Result Event."""
wx.PyEvent.__init__(self)
self.SetEventType(EVT_RESULT_ID)
self.data = data # Thread class that executes processing
class WorkerThread(Thread):
"""Worker Thread Class."""
def __init__(self, notify_window):
"""Init Worker Thread Class."""
Thread.__init__(self)
self.setDaemon(1)
self._notify_window = notify_window
self._want_abort = 0
# This starts the thread running on creation, but you could
# also make the GUI thread responsible for calling this
self.start() def run(self):
"""Run Worker Thread."""
# This is the code executing in the new thread. Simulation of
for i in range(10):
time.sleep(1)
if self._want_abort:
# Use a result of None to acknowledge the abort (of
# course you can use whatever you'd like or even
# a separate event type)
wx.PostEvent(self._notify_window, ResultEvent(None))
return
wx.PostEvent(self._notify_window, ResultEvent(i))
# Here's where the result would be returned (this is an
# example fixed result of the number 10, but it could be
# any Python object)
wx.PostEvent(self._notify_window, ResultEvent(10)) def abort(self):
"""abort worker thread."""
# Method for use by main thread to signal an abort
self._want_abort = 1 # GUI Frame class that spins off the worker thread
class MainFrame(wx.Frame):
"""Class MainFrame."""
def __init__(self, parent, id):
"""Create the MainFrame."""
wx.Frame.__init__(self, parent, id, 'Thread Test') # Dumb sample frame with two buttons
self.OkButton = wx.Button(self, ID_START, 'Start', pos=(0,0))
wx.Button(self, ID_STOP, 'Stop', pos=(0,50))
self.status = wx.StaticText(self, -1, '', pos=(0,100)) self.Bind(wx.EVT_BUTTON, self.OnStart, id=ID_START)
self.Bind(wx.EVT_BUTTON, self.OnStop, id=ID_STOP) # Set up event handler for any worker thread results
EVT_RESULT(self,self.OnResult) # And indicate we don't have a worker thread yet
self.worker = None def __Onfunc(self):
import time
time.sleep(10) def OnStart(self, event):
"""Start Computation."""
# Trigger the worker thread unless it's already busy
if not self.worker:
self.status.SetLabel('Starting computation')
self.worker = WorkerThread(self) def OnStop(self, event):
"""Stop Computation."""
# Flag the worker thread to stop if running
if self.worker:
self.status.SetLabel('Trying to abort computation')
self.worker.abort() def OnResult(self, event):
"""Show Result status.""" # Process results here
self.status.SetLabel('Computation Result: %s' % event.data)
# In either event, the worker is done
self.worker = None class MainApp(wx.App):
"""Class Main App."""
def OnInit(self):
"""Init Main App."""
self.frame = MainFrame(None, -1)
self.frame.Show(True)
self.SetTopWindow(self.frame)
return True if __name__ == '__main__':
app = MainApp(0)
app.MainLoop()

wxpython线程安全的方法的更多相关文章

  1. 线程的Abort方法有感

    今天看CSDN上一个很老的帖子,有个人说Thread.Abort()方法调用之后一定会抛出异常,我对这个有点疑问. 于是自己做了一个测试demo,来研究Abort抛出异常的时机.废话少说,直接上代码: ...

  2. Java中怎样创建线程安全的方法

    面试问题: 下面的方法是否线程安全?怎样让它成为线程安全的方法? class MyCounter { private static int counter = 0; public static int ...

  3. WPF / Win Form:多线程去修改或访问UI线程数据的方法( winform 跨线程访问UI控件 )

    WPF:谈谈各种多线程去修改或访问UI线程数据的方法http://www.cnblogs.com/mgen/archive/2012/03/10/2389509.html 子线程非法访问UI线程的数据 ...

  4. C#中的几个线程同步对象方法

    在编写多线程程序时无可避免会遇到线程的同步问题.什么是线程的同步呢? 举个例子:如果在一个公司里面有一个变量记录某人T的工资count=100,有两个主管A和B(即工作线程)在早一些时候拿了这个变量的 ...

  5. 多线程---其他方法 停止线程、守护线程、join方法

    第三方停止线程: 原来是stop(),因为该方法有些问题,所以被interrupt()方法取代,它的用途跟机制是 当没有指定的方式让冻结的线程恢复到运行状态时,这时需要对冻结进行清除,强制让线程恢复到 ...

  6. 线程的实现方法以及区别 extends Thread、implements Runable

    /** 线程存在于进程当中,进程由系统创建. 创建新的执行线程有两种方法 注意:   线程复写run方法,然后用start()方法调用,其实就是调用的run()方法,只是如果直接启动run()方法, ...

  7. java多线程之守护线程以及Join方法

    版权声明:本文出自汪磊的博客,转载请务必注明出处. 一.守护线程概述及示例 守护线程就是为其它线程提供"守护"作用,说白了就是为其它线程服务的,比如GC线程. java程序中线程分 ...

  8. 启动线程用start方法

    启动线程用start方法而不是用run方法 public static void main(String[] args) { Thread t=new Thread("Thread-TEST ...

  9. 线程的使用方法start run sleep join

    今天回顾了Java的线程的一些知识 例1:下面代码存有详细的解释 主要是继承Thread类与实现Runnable接口 以及start()和run()方法 package com.date0607; / ...

随机推荐

  1. maven src/test/resources 下的logback-test.xml 读取 properties文件中的key-value值

    <profiles>        <profile>            <id>test-cd</id>            <prope ...

  2. 启动tomcat时报classpath not found

    启动tomcat时报classpath  not found 原因是缺包,首先查看tomcat安装地址,然后找到webapps目录下,找到该项目,看lib下是否缺包,不能单纯的看项目下是否缺包.

  3. C++重载解析

    重载解析(overloading resolution)的规则决定了编译器为一个函数调用选用哪个函数定义.一般过程如下: 将名称相同的函数/模板函数找到并创建候选列表 从中挑选参数数目正确,符合完全匹 ...

  4. Real-Rime Rendering (2) - 变换和矩阵(Translation and Matrics)

    提要 在图形的计算中,比如旋转.缩放.平移.投影等操作,矩阵都扮演着极其重要的角色,它是操作图元的基本工具.虽然很多的图形API已经封装好了这些矩阵操作,但是理解这些矩阵操作的原理会非常非常有帮助,比 ...

  5. uva:10340 - All in All(字符串匹配)

    题目:10340 - All in All 题目大意:给出字符串s和t,问s是否是t的子串.s若去掉某些字符能和t一样,那么t是s的子串. 解题思路:匹配字符.t的每一个字符和s中的字符匹配.注意这里 ...

  6. Adblock Plus完美过滤视频网站广告、无黑屏!及屏蔽非本站脚本的Adblock Plus过滤器语法之探讨

    测试用浏览器:Firefox 24.订阅的Adblock Plus过滤规则有默认的 ChinaList + EasyList,和国内视频广告规则[Yge.me],其网址:http://i.yge.me ...

  7. SCI科技论文写作技巧-核心价值

    第一次写SCI论文写作技巧,本身不是大牛,也许没有资金格谈论这个. 这里仅仅是一些个人思考,不正确,好还是不好.而当另一种理论. 对于工程专业的学生,谁往往应用,书写SCI事情.当然,也不是没可能.全 ...

  8. Ubuntu知识记录

    1.激活root用户:sudo passwd root 2.安装ftp:apt-get install vsftpd,修改配置文件/etc/vsftpd.conf write_enable=yes表明 ...

  9. Linux 基本命令(持续更新ing)

    cd -> 变换路径                        //文件一般存在/var/路径下,var为可修改存储盘 ls -> 列出所有隐藏文件与相关文件的属性   #ls -al ...

  10. uva 1391 Astronauts(2-SAT)

    /*翻译好题意 n个变量 不超过m*2句话*/ #include<iostream> #include<cstdio> #include<cstring> #inc ...