1 /////////////////////////////////////////////////////////////////////////////
3 // Purpose: wxWindows thread sample
4 // Author: Julian Smart(minimal)/Guilhem Lavaux(thread test)
8 // Copyright: (c) Julian Smart, Markus Holzem, Guilhem Lavaux
9 // Licence: wxWindows license
10 /////////////////////////////////////////////////////////////////////////////
15 1. show how SetPriority() works.
16 2. use worker threads to update progress controls instead of writing
17 messages - it will be more visual
21 #pragma implementation "test.cpp"
22 #pragma interface "test.cpp"
25 // For compilers that support precompilation, includes "wx/wx.h".
26 #include "wx/wxprec.h"
37 #error "This sample requires thread support!"
38 #endif // wxUSE_THREADS
40 #include "wx/thread.h"
41 #include "wx/dynarray.h"
44 // Define a new application type
45 class MyApp
: public wxApp
52 WX_DEFINE_ARRAY(wxThread
*, wxArrayThread
);
54 // Define a new frame type
55 class MyFrame
: public wxFrame
59 MyFrame(wxFrame
*frame
, const wxString
& title
, int x
, int y
, int w
, int h
);
62 void WriteText(const wxString
& text
) { m_txtctrl
->WriteText(text
); }
65 void OnQuit(wxCommandEvent
& event
);
66 void OnAbout(wxCommandEvent
& event
);
67 void OnClear(wxCommandEvent
& event
);
69 void OnStartThread(wxCommandEvent
& event
);
70 void OnStartThreads(wxCommandEvent
& event
);
71 void OnStopThread(wxCommandEvent
& event
);
72 void OnPauseThread(wxCommandEvent
& event
);
73 void OnResumeThread(wxCommandEvent
& event
);
75 void OnIdle(wxIdleEvent
&event
);
77 // called by dying thread _in_that_thread_context_
78 void OnThreadExit(wxThread
*thread
);
81 // helper function - creates a new thread (but doesn't run it)
82 MyThread
*CreateThread();
84 // crit section protects access to all of the arrays below
85 wxCriticalSection m_critsect
;
87 // all the threads currently alive - as soon as the thread terminates, it's
88 // removed from the array
89 wxArrayThread m_threads
;
91 // both of these arrays are only valid between 2 iterations of OnIdle(),
92 // they're cleared each time it is excuted.
94 // the array of threads which finished (either because they did their work
95 // or because they were explicitly stopped)
96 wxArrayThread m_terminated
;
98 // the array of threads which were stopped by the user and not terminated
99 // by themselves - these threads shouldn't be Delete()d second time from
101 wxArrayThread m_stopped
;
103 // just some place to put our messages in
104 wxTextCtrl
*m_txtctrl
;
106 // remember the number of running threads and total number of threads
107 size_t m_nRunning
, m_nCount
;
109 DECLARE_EVENT_TABLE()
112 class MyThread
: public wxThread
115 MyThread(MyFrame
*frame
);
117 // thread execution starts here
118 virtual void *Entry();
120 // called when the thread exits - whether it terminates normally or is
121 // stopped with Delete() (but not when it is Kill()ed!)
122 virtual void OnExit();
124 // write something to the text control
125 void WriteText(const wxString
& text
);
132 MyThread::MyThread(MyFrame
*frame
)
139 void MyThread::WriteText(const wxString
& text
)
142 msg
<< wxTime().FormatTime() << ": " << text
;
144 // before doing any GUI calls we must ensure that this thread is the only
146 wxMutexGuiLocker guiLocker
;
148 m_frame
->WriteText(msg
);
151 void MyThread::OnExit()
153 m_frame
->OnThreadExit(this);
156 void *MyThread::Entry()
160 text
.Printf("Thread 0x%x started.\n", GetID());
163 for ( m_count
= 0; m_count
< 10; m_count
++ )
165 // check if we were asked to exit
169 text
.Printf("[%u] Thread 0x%x here.\n", m_count
, GetID());
172 // wxSleep() can't be called from non-GUI thread!
173 wxThread::Sleep(1000);
176 text
.Printf("Thread 0x%x finished.\n", GetID());
182 // ID for the menu commands
189 TEST_START_THREAD
= 201,
196 BEGIN_EVENT_TABLE(MyFrame
, wxFrame
)
197 EVT_MENU(TEST_QUIT
, MyFrame::OnQuit
)
198 EVT_MENU(TEST_ABOUT
, MyFrame::OnAbout
)
199 EVT_MENU(TEST_CLEAR
, MyFrame::OnClear
)
200 EVT_MENU(TEST_START_THREAD
, MyFrame::OnStartThread
)
201 EVT_MENU(TEST_START_THREADS
, MyFrame::OnStartThreads
)
202 EVT_MENU(TEST_STOP_THREAD
, MyFrame::OnStopThread
)
203 EVT_MENU(TEST_PAUSE_THREAD
, MyFrame::OnPauseThread
)
204 EVT_MENU(TEST_RESUME_THREAD
, MyFrame::OnResumeThread
)
206 EVT_IDLE(MyFrame::OnIdle
)
209 // Create a new application object
210 IMPLEMENT_APP (MyApp
)
212 // `Main program' equivalent, creating windows and returning main app frame
215 // Create the main frame window
216 MyFrame
*frame
= new MyFrame((wxFrame
*)NULL
, "wxWindows threads sample",
220 wxMenu
*file_menu
= new wxMenu
;
222 file_menu
->Append(TEST_CLEAR
, "&Clear log");
223 file_menu
->AppendSeparator();
224 file_menu
->Append(TEST_ABOUT
, "&About");
225 file_menu
->AppendSeparator();
226 file_menu
->Append(TEST_QUIT
, "E&xit");
227 wxMenuBar
*menu_bar
= new wxMenuBar
;
228 menu_bar
->Append(file_menu
, "&File");
230 wxMenu
*thread_menu
= new wxMenu
;
231 thread_menu
->Append(TEST_START_THREAD
, "&Start a new thread");
232 thread_menu
->Append(TEST_START_THREADS
, "Start &many threads at once");
233 thread_menu
->Append(TEST_STOP_THREAD
, "S&top a running thread");
234 thread_menu
->AppendSeparator();
235 thread_menu
->Append(TEST_PAUSE_THREAD
, "&Pause a running thread");
236 thread_menu
->Append(TEST_RESUME_THREAD
, "&Resume suspended thread");
237 menu_bar
->Append(thread_menu
, "&Thread");
238 frame
->SetMenuBar(menu_bar
);
248 // My frame constructor
249 MyFrame::MyFrame(wxFrame
*frame
, const wxString
& title
,
250 int x
, int y
, int w
, int h
)
251 : wxFrame(frame
, -1, title
, wxPoint(x
, y
), wxSize(w
, h
))
253 m_nRunning
= m_nCount
= 0;
257 m_txtctrl
= new wxTextCtrl(this, -1, "", wxPoint(0, 0), wxSize(0, 0),
258 wxTE_MULTILINE
| wxTE_READONLY
);
262 MyThread
*MyFrame::CreateThread()
264 MyThread
*thread
= new MyThread(this);
266 if ( thread
->Create() != wxTHREAD_NO_ERROR
)
268 wxLogError("Can't create thread!");
271 wxCriticalSectionLocker
enter(m_critsect
);
272 m_threads
.Add(thread
);
277 void MyFrame::OnStartThreads(wxCommandEvent
& WXUNUSED(event
) )
279 static wxString s_str
;
280 s_str
= wxGetTextFromUser("How many threads to start: ",
283 if ( s_str
.IsEmpty() )
287 sscanf(s_str
, "%u", &count
);
291 wxArrayThread threads
;
293 // first create them all...
294 for ( n
= 0; n
< count
; n
++ )
296 threads
.Add(CreateThread());
300 msg
.Printf("%d new threads created.", count
);
301 SetStatusText(msg
, 1);
303 // ...and then start them
304 for ( n
= 0; n
< count
; n
++ )
310 void MyFrame::OnStartThread(wxCommandEvent
& WXUNUSED(event
) )
312 MyThread
*thread
= CreateThread();
314 if ( thread
->Run() != wxTHREAD_NO_ERROR
)
316 wxLogError("Can't start thread!");
319 SetStatusText("New thread started.", 1);
322 void MyFrame::OnStopThread(wxCommandEvent
& WXUNUSED(event
) )
324 // stop the last thread
325 if ( m_threads
.IsEmpty() )
327 wxLogError("No thread to stop!");
333 wxThread
*thread
= m_threads
.Last();
334 m_stopped
.Add(thread
);
336 // it's important to leave critical section before calling Delete()
337 // because delete will (implicitly) call OnThreadExit() which also tries
338 // to enter the same crit section - would dead lock.
343 SetStatusText("Thread stopped.", 1);
347 void MyFrame::OnResumeThread(wxCommandEvent
& WXUNUSED(event
) )
349 wxCriticalSectionLocker
enter(m_critsect
);
351 // resume first suspended thread
352 size_t n
= 0, count
= m_threads
.Count();
353 while ( n
< count
&& !m_threads
[n
]->IsPaused() )
358 wxLogError("No thread to resume!");
362 m_threads
[n
]->Resume();
364 SetStatusText("Thread resumed.", 1);
368 void MyFrame::OnPauseThread(wxCommandEvent
& WXUNUSED(event
) )
370 wxCriticalSectionLocker
enter(m_critsect
);
372 // pause last running thread
373 int n
= m_threads
.Count() - 1;
374 while ( n
>= 0 && !m_threads
[n
]->IsRunning() )
379 wxLogError("No thread to pause!");
383 m_threads
[n
]->Pause();
385 SetStatusText("Thread paused.", 1);
389 // set the frame title indicating the current number of threads
390 void MyFrame::OnIdle(wxIdleEvent
&event
)
392 // first wait for all the threads which dies since the last call
394 wxCriticalSectionLocker
enter(m_critsect
);
396 size_t nCount
= m_terminated
.GetCount();
397 for ( size_t n
= 0; n
< nCount
; n
++ )
399 // don't delete the threads which were stopped - they were already
400 // deleted in OnStopThread()
401 wxThread
*thread
= m_terminated
[n
];
402 if ( m_stopped
.Index(thread
) == wxNOT_FOUND
)
407 m_terminated
.Empty();
411 nCount
= m_threads
.Count();
412 for ( size_t n
= 0; n
< nCount
; n
++ )
414 if ( m_threads
[n
]->IsRunning() )
418 if ( nCount
!= m_nCount
|| nRunning
!= m_nRunning
)
420 m_nRunning
= nRunning
;
423 wxLogStatus(this, "%u threads total, %u running.", nCount
, nRunning
);
425 //else: avoid flicker - don't print anything
428 void MyFrame::OnQuit(wxCommandEvent
& WXUNUSED(event
) )
430 size_t count
= m_threads
.Count();
431 for ( size_t i
= 0; i
< count
; i
++ )
433 m_threads
[i
]->Delete();
439 void MyFrame::OnAbout(wxCommandEvent
& WXUNUSED(event
) )
441 wxMessageDialog
dialog(this, "wxWindows multithreaded application sample\n"
442 "(c) 1998 Julian Smart, Guilhem Lavaux\n"
443 "(c) 1999 Vadim Zeitlin",
444 "About wxThread sample",
445 wxOK
| wxICON_INFORMATION
);
450 void MyFrame::OnClear(wxCommandEvent
& WXUNUSED(event
))
455 void MyFrame::OnThreadExit(wxThread
*thread
)
457 wxCriticalSectionLocker
enter(m_critsect
);
459 m_threads
.Remove(thread
);
460 m_terminated
.Add(thread
);