wxpython线程安全的方法
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线程安全的方法的更多相关文章
- 线程的Abort方法有感
今天看CSDN上一个很老的帖子,有个人说Thread.Abort()方法调用之后一定会抛出异常,我对这个有点疑问. 于是自己做了一个测试demo,来研究Abort抛出异常的时机.废话少说,直接上代码: ...
- Java中怎样创建线程安全的方法
面试问题: 下面的方法是否线程安全?怎样让它成为线程安全的方法? class MyCounter { private static int counter = 0; public static int ...
- WPF / Win Form:多线程去修改或访问UI线程数据的方法( winform 跨线程访问UI控件 )
WPF:谈谈各种多线程去修改或访问UI线程数据的方法http://www.cnblogs.com/mgen/archive/2012/03/10/2389509.html 子线程非法访问UI线程的数据 ...
- C#中的几个线程同步对象方法
在编写多线程程序时无可避免会遇到线程的同步问题.什么是线程的同步呢? 举个例子:如果在一个公司里面有一个变量记录某人T的工资count=100,有两个主管A和B(即工作线程)在早一些时候拿了这个变量的 ...
- 多线程---其他方法 停止线程、守护线程、join方法
第三方停止线程: 原来是stop(),因为该方法有些问题,所以被interrupt()方法取代,它的用途跟机制是 当没有指定的方式让冻结的线程恢复到运行状态时,这时需要对冻结进行清除,强制让线程恢复到 ...
- 线程的实现方法以及区别 extends Thread、implements Runable
/** 线程存在于进程当中,进程由系统创建. 创建新的执行线程有两种方法 注意: 线程复写run方法,然后用start()方法调用,其实就是调用的run()方法,只是如果直接启动run()方法, ...
- java多线程之守护线程以及Join方法
版权声明:本文出自汪磊的博客,转载请务必注明出处. 一.守护线程概述及示例 守护线程就是为其它线程提供"守护"作用,说白了就是为其它线程服务的,比如GC线程. java程序中线程分 ...
- 启动线程用start方法
启动线程用start方法而不是用run方法 public static void main(String[] args) { Thread t=new Thread("Thread-TEST ...
- 线程的使用方法start run sleep join
今天回顾了Java的线程的一些知识 例1:下面代码存有详细的解释 主要是继承Thread类与实现Runnable接口 以及start()和run()方法 package com.date0607; / ...
随机推荐
- Web 测试笔记
测试难点 主要是模块之间的同步问题. 测试容易忽略的地方 1. 各种标题.包括页面“标签页”的标题,弹出框的标题.由于开发经常直接用之前的页面,比如编辑可能直接用新增的页面,导致标题出错. 2. 最大 ...
- Java Spring的 JavaConfig 注解
序 传统spring一般都是基于xml配置的,不过后来新增了许多JavaConfig的注解.特别是springboot,基本都是清一色的java config,不了解一下,还真是不适应.这里备注一下. ...
- poj2299
好吧,看到这个图片就知道是干什么的了,求逆序数- - 可以用线段树,貌似还可以用归并排序,这题应该是考的归并排序,毕竟是递归分治- - 基本上都忘了,再写一写试试吧. AC ///////////// ...
- Spring 报错:Error creating bean with name
org.springframework.beans.factory.BeanCreationException: 原因是在autowire时,找不到相应的类,上述问题是因为XXXXX的实现类中没有加相 ...
- eclipse下开发简单的Web Service
service部分 在eclipse下新建一个动态web项目 在项目中新建一个service类 编写SayHello类的代码 package org.sunny.service; //包不要引用错了 ...
- Ubuntu中使用终端运行Hadoop程序
接上一篇<Ubuntu Kylin系统下安装Hadoop2.6.0> 通过上一篇,Hadoop伪分布式基本配好了. 下一步是运行一个MapReduce程序,以WordCount为例: 1. ...
- Codeforces 437B The Child and Set
题目链接:Codeforces 437B The Child and Set 開始是想到了这样的情况,比方lowbit之后从大到小排序后有这么几个数,200.100,60.50.S = 210.那先选 ...
- C#编写QQ找茬外挂
QQ找茬外挂,用C#代码编写. 使用方法 这个工具的主要运行流程很简单:游戏截图->比较图片->标记图片不同点.实现代码 截图的处理类ScreenCapture: /// /// 提供全屏 ...
- Android(java)学习笔记228:服务(service)之绑定服务调用服务里面的方法
1.绑定服务调用服务里面的方法,图解: 步骤: (1)在Activity代码里面绑定 bindService(),以bind的方式开启服务 : bindServ ...
- Cookie的读写
记住怎么写就可以了,不要问我为什么=_= 设置值的页面:context.Response.SetCookie(new HttpCookie("username",username) ...