473,657 Members | 2,351 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Design Question: GUI+Threads.

Hi All,

I am tinkering with a stock-market analysis program that needs to have (at
least one) a worker thread for processing real-time data and a GUI where one
can control/monitor the function of the worker, set parameters and so forth.

Is there an elegant and generic way to implement the typical "Model, View,
Controller" pattern so that the "Model+Controll er" execute in the context of
the worker thread and the "View" will execute in the GUI thread - and
communication between the two is thread-safe and simple?


Jul 18 '05 #1
5 4861
"Frithiof Andreas Jensen" <fr************ *@removethis.te d.ericsson.dk> writes:
Hi All,

I am tinkering with a stock-market analysis program that needs to have (at
least one) a worker thread for processing real-time data and a GUI where one
can control/monitor the function of the worker, set parameters and so forth.

Is there an elegant and generic way to implement the typical "Model, View,
Controller" pattern so that the "Model+Controll er" execute in the context of
the worker thread and the "View" will execute in the GUI thread - and
communication between the two is thread-safe and simple?


One way to do it:

Use two Queue.Queue's. Do non blocking get's and put's from the gui on
a timer. Do blocking gets from the queue instance that the GUI calls
put on, do blocking put's on the queue that the GUI calls get from.

I usually wrap the use of Queue behind a method interface, so that the
GUI calls methods on the threaded class to get and put. If you want to
to use a thread pool you can easily make all the threads can share the
queue instances.

Jul 18 '05 #2
Syver Enstad wrote:
"Frithiof Andreas Jensen" <fr************ *@removethis.te d.ericsson.dk> writes:

Hi All,

I am tinkering with a stock-market analysis program that needs to have (at
least one) a worker thread for processing real-time data and a GUI where one
can control/monitor the function of the worker, set parameters and so forth.

Is there an elegant and generic way to implement the typical "Model, View,
Controller" pattern so that the "Model+Controll er" execute in the context of
the worker thread and the "View" will execute in the GUI thread - and
communicati on between the two is thread-safe and simple?


You might make your life easier by having the controller and the view be
on the main thread and dispatch a new model to the work thread.

Contoller -> starts or attaches to view
-> starts a new model

model -> signals events to controller which updates view
controller -> sets model states when necessary.

Usually you can wrap model events into gui events and let the gui's
mainloop sort them out and dispatch them to the controllers callbacks.

In python it is thread safe to set variables across the thread boundary,
the model will have to check for these variables changing though. The
standard variable is set by thread.kill() see the threading module for
more details.

What gui framework are you using?

Brian Kelley

Jul 18 '05 #3
Thaks for the reply,

"Brian Kelley" <bk*****@wi.mit .edu> wrote in message
news:3f******** *************@s enator-bedfellow.mit.e du...
Syver Enstad wrote:
You might make your life easier by having the controller and the view be
on the main thread and dispatch a new model to the work thread.
Hmm. I think that makes sense, since it is the GUI that "demands"
attention - I was doing sort-of the other way round by having a thread
dispatching messages to models AND the GUI thread....
Usually you can wrap model events into gui events and let the gui's
mainloop sort them out and dispatch them to the controllers callbacks.
So, To make sure that I understand correctly:

I will have one Controller per Worker; the Controller interacts with the GUI
and it is the Controller that "understand s" that the Worker is running in a
separate thread and maps GUI/Worker events across the thread boundary by
some means -

I was planning to use of a Dispatcher/Mailbox System:

The worker thread(S) blocks on an input queue until a message is in that
queue - then the worker thread process the message and places a result in an
output queue. The results in the output queue(s) of each worker are read by
the main thread and placed in the input queues of other workers or in the
GUI.....most of the time a worker will sleep, waiting for work.

The input and output queues would be owned by the workers, the "distributi on
lists" i.e. which event goes where would be owned by a "Dispatcher " running
in the main thread .

While this is fine for Data, setting parameters etc. is clumsy: One needs to
setup a filter to sort parameter messages from the data and do special
processing - i would rather keep only data in the message loop.
In python it is thread safe to set variables across the thread boundary,
the model will have to check for these variables changing though.
....I will need locking in the models setXyz() methods so that I do not stomp
on some data that the worker thread is using?
What gui framework are you using?


wxPython - in the hope that SciPy eventually will do a Python 2.2.3 release,
so that by the time I need it, I can get my hands on all those neat
Plotting, Numeric and Stats tools waiting to be liberated ;-)
Jul 18 '05 #4
Frithiof Andreas Jensen wrote:
Thaks for the reply,

"Brian Kelley" <bk*****@wi.mit .edu> wrote in message
news:3f******** *************@s enator-bedfellow.mit.e du...
Syver Enstad wrote:


You might make your life easier by having the controller and the view be
on the main thread and dispatch a new model to the work thread.

Hmm. I think that makes sense, since it is the GUI that "demands"
attention - I was doing sort-of the other way round by having a thread
dispatching messages to models AND the GUI thread....

<snip>
I was planning to use of a Dispatcher/Mailbox System:

The worker thread(S) blocks on an input queue until a message is in that
queue - then the worker thread process the message and places a result in an
output queue. The results in the output queue(s) of each worker are read by
the main thread and placed in the input queues of other workers or in the
GUI.....most of the time a worker will sleep, waiting for work.


This seems very doable. You have at least two options: 1) use a wxTimer
to periodically tell the controller to check the worker's output queues
or 2) have the worker send a new wxEvent to the view with the result
data. This could be as simple as:

wxEVT_WORKER_RE SULT = wxNewEventType( )

def EVT_WORKER_RESU LT(win, func):
win.Connect(-1, -1, wxEVT_WORKER_RE SULT, func)

class WorkerResultEve nt(wxPyEvent):
def __init__(self, result):
wxPyEvent.__ini t__(self)
self.SetEventTy pe(wxEVT_WORKER _RESULT)
self.data = data

# event wrapper so that the worker thread can send
# results
class EventWrapper:
def __init__(self, window):
self.window = window
def setResult(self, data):
wxPostEvent(sel f.win, WorkerResultEve nt(data))

class WorkerThread(th read):
def __init__(self, eventSender):
...
def Run(self): ...
...
self.eventSende r(result)
self.blockForNe xtJob()

class View:
def __init__(self, controller,...) :
EVT_WORKER_RESU LT(self, self.OnResult)
def OnResult(self, evt):
self.controller .OnResult(evt.r esult)

A good example of this is in the wxPython thread example. Their view is
their controller though.

Jul 18 '05 #5

"Brian Kelley" <bk*****@wi.mit .edu> wrote in message
news:z6cmb.1830 6$Tr4.37514@att bi_s03...
Frithiof Andreas Jensen wrote:


Thanks for the replies - I think I can come up with something now.
Jul 18 '05 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

32
3172
by: Christopher Benson-Manica | last post by:
Is the following code legal, moral, and advisable? #include <iostream> class A { private: int a; public: A() : a(42) {}
9
3251
by: perchef | last post by:
Hi, I have several files to download and a GUI to update. I know this is a frequently asked question but i can't find an appropriate solution. My Downloader extends threading.Thread and update a wx.Gauge in GUI during the process. for src in urls: downloader = Downloader( src, destination, GUI ) downloader.start()
11
4253
by: Nenad Dobrilovic | last post by:
Hi, I have big problem. I made generic form which can be rendered, and as a result of that action, I get System.Windows.Forms.Form object. Rendering must be done in GUI thread (one which has message pump), but I can't garantee that the using of Render function will be made in GUI thread. This is Render function: public object Render(Synchronizer.T sync) { return sync.Render(this); <-- this function is making real Form
5
2036
by: Robert W. | last post by:
I'm creating a WinForms app that will act as a companion (think administrator functionality) to a Pocket PC app. Generally the WinForms app works under just the UI thread. But if a Pocket PC connects to the desktop via ActiveSync then a separate thread is spawned. In addition to the main desktop app window I also have a Notification form that appears in the lower right of the screen and provides feedback to the user about what is...
0
1614
by: Dave Coate | last post by:
I am working on a generic way to launch multiple similar processes (threads) at once, but limit the number of threads running at any one time to a number I set. As I understand it the following line makes a Queue "thread safe", so I do not need to explicitly lock and unlock it when multiple threads are working with it. 'Thread safe queue Private IndexQueue As Queue = Queue.Synchronized(New Queue)
2
9570
by: Kevin Walzer | last post by:
I'm trying to decide whether I need threads in my Tkinter application or not. My app is a front end to a command-line tool; it feeds commands to the command-line program, then reads its output and displays it in a Tkinter text widget. Some of the commands are long-running and/or return thousands of lines of output. I initially thought I needed to use threading, because the GUI would block when reading the output, even when I configured...
0
1063
by: bernhard.voigt | last post by:
Dear list, I'm using two external modules (matplotlib and pyroot). Both are using different GUI threads (internally) Unfortunately, pretty soon after I've loaded both modules and made some function calls (without invoking GUI commands), python dies with a segfault. A libthread_db captures the stack trace. My python version is 2.5 and I'm on a Scientific Linux 5 system. *** Break *** segmentation violation
10
3425
by: S James S Stapleton | last post by:
Is volatile necessary anymore? I have a two-thread piece of code I've been testing to figure out what volatile does (fairly simple code, uses pthreads). I have an update thread (variables passed as volatile) and a print thread (one variable volatile, the other, not). There is no difference in the behavior of the volatile and nonvolatile thread. I'm compiling this with gcc, using the -O2 and -pthreads flags. The sudocode is at the end....
35
2060
by: Alessio Sangalli | last post by:
Hi all. I am writing the documentation for the program I'm going to develop (yes, documentation before the implementation, it's awesome!). In short, it will run on an embedded platform wint Linux as OS. I have some hardware devices that have to send data to and receive data from a server on the network. I will use one TCP stream for all the communication. Basically what I plan to do is the following: - for the program to be as modular...
0
8399
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8312
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8732
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8504
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8606
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7337
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
4159
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
2732
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
1622
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.