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 /////////////////////////////////////////////////////////////////////////////
13 TODO: use worker threads to update progress controls instead of writing
14 messages - it will be more visual
18 #pragma implementation "test.cpp"
19 #pragma interface "test.cpp"
22 // For compilers that support precompilation, includes "wx/wx.h".
23 #include "wx/wxprec.h"
34 #error "This sample requires thread support!"
35 #endif // wxUSE_THREADS
37 #include "wx/thread.h"
38 #include "wx/dynarray.h"
42 WX_DEFINE_ARRAY(wxThread
*, wxArrayThread
);
44 // Define a new application type
45 class MyApp
: public wxApp
48 virtual bool OnInit();
51 // all the threads currently alive - as soon as the thread terminates, it's
52 // removed from the array
53 wxArrayThread m_threads
;
55 // crit section protects access to all of the arrays below
56 wxCriticalSection m_critsect
;
59 // Create a new application object
62 // Define a new frame type
63 class MyFrame
: public wxFrame
67 MyFrame(wxFrame
*frame
, const wxString
& title
, int x
, int y
, int w
, int h
);
70 void WriteText(const wxString
& text
) { m_txtctrl
->WriteText(text
); }
73 void OnQuit(wxCommandEvent
& event
);
74 void OnAbout(wxCommandEvent
& event
);
75 void OnClear(wxCommandEvent
& event
);
77 void OnStartThread(wxCommandEvent
& event
);
78 void OnStartThreads(wxCommandEvent
& event
);
79 void OnStopThread(wxCommandEvent
& event
);
80 void OnPauseThread(wxCommandEvent
& event
);
81 void OnResumeThread(wxCommandEvent
& event
);
83 void OnStartWorker(wxCommandEvent
& event
);
84 void OnWorkerEvent(wxCommandEvent
& event
);
86 void OnIdle(wxIdleEvent
&event
);
89 // helper function - creates a new thread (but doesn't run it)
90 MyThread
*CreateThread();
92 // just some place to put our messages in
93 wxTextCtrl
*m_txtctrl
;
95 // remember the number of running threads and total number of threads
96 size_t m_nRunning
, m_nCount
;
101 // ID for the menu commands
108 TEST_START_THREAD
= 201,
114 WORKER_EVENT
// this one gets sent from the worker thread
117 //--------------------------------------------------
119 //--------------------------------------------------
121 class MyThread
: public wxThread
124 MyThread(MyFrame
*frame
);
126 // thread execution starts here
127 virtual void *Entry();
129 // called when the thread exits - whether it terminates normally or is
130 // stopped with Delete() (but not when it is Kill()ed!)
131 virtual void OnExit();
133 // write something to the text control
134 void WriteText(const wxString
& text
);
141 MyThread::MyThread(MyFrame
*frame
)
148 void MyThread::WriteText(const wxString
& text
)
152 // before doing any GUI calls we must ensure that this thread is the only
159 m_frame
->WriteText(msg
);
164 void MyThread::OnExit()
166 wxCriticalSectionLocker
locker(wxGetApp().m_critsect
);
168 wxGetApp().m_threads
.Remove(this);
171 void *MyThread::Entry()
175 text
.Printf("Thread 0x%x started (priority = %d).\n",
176 GetId(), GetPriority());
179 for ( m_count
= 0; m_count
< 10; m_count
++ )
181 // check if we were asked to exit
185 text
.Printf("[%u] Thread 0x%x here.\n", m_count
, GetId());
188 // wxSleep() can't be called from non-GUI thread!
189 wxThread::Sleep(1000);
192 text
.Printf("Thread 0x%x finished.\n", GetId());
198 //--------------------------------------------------
200 //--------------------------------------------------
202 class MyWorkerThread
: public wxThread
205 MyWorkerThread(MyFrame
*frame
);
207 // thread execution starts here
208 virtual void *Entry();
210 // called when the thread exits - whether it terminates normally or is
211 // stopped with Delete() (but not when it is Kill()ed!)
212 virtual void OnExit();
219 MyWorkerThread::MyWorkerThread(MyFrame
*frame
)
226 void MyWorkerThread::OnExit()
230 void *MyWorkerThread::Entry()
232 for ( m_count
= 0; m_count
< 10; m_count
++ )
234 // check if we were asked to exit
238 wxCommandEvent
event( wxEVT_COMMAND_MENU_SELECTED
, WORKER_EVENT
);
239 event
.SetInt( WORKER_EVENT
);
240 wxPostEvent( m_frame
, event
);
242 // wxSleep() can't be called from non-GUI thread!
243 wxThread::Sleep(1000);
249 //--------------------------------------------------
251 //--------------------------------------------------
253 BEGIN_EVENT_TABLE(MyFrame
, wxFrame
)
254 EVT_MENU(TEST_QUIT
, MyFrame::OnQuit
)
255 EVT_MENU(TEST_ABOUT
, MyFrame::OnAbout
)
256 EVT_MENU(TEST_CLEAR
, MyFrame::OnClear
)
257 EVT_MENU(TEST_START_THREAD
, MyFrame::OnStartThread
)
258 EVT_MENU(TEST_START_THREADS
, MyFrame::OnStartThreads
)
259 EVT_MENU(TEST_STOP_THREAD
, MyFrame::OnStopThread
)
260 EVT_MENU(TEST_PAUSE_THREAD
, MyFrame::OnPauseThread
)
261 EVT_MENU(TEST_RESUME_THREAD
, MyFrame::OnResumeThread
)
263 EVT_MENU(TEST_START_WORKER
, MyFrame::OnStartWorker
)
264 EVT_MENU(WORKER_EVENT
, MyFrame::OnWorkerEvent
)
266 EVT_IDLE(MyFrame::OnIdle
)
269 // `Main program' equivalent, creating windows and returning main app frame
272 // Create the main frame window
273 MyFrame
*frame
= new MyFrame((wxFrame
*)NULL
, "wxWindows threads sample",
277 wxMenu
*file_menu
= new wxMenu
;
279 file_menu
->Append(TEST_CLEAR
, "&Clear log\tCtrl-L");
280 file_menu
->AppendSeparator();
281 file_menu
->Append(TEST_ABOUT
, "&About");
282 file_menu
->AppendSeparator();
283 file_menu
->Append(TEST_QUIT
, "E&xit\tAlt-X");
284 wxMenuBar
*menu_bar
= new wxMenuBar
;
285 menu_bar
->Append(file_menu
, "&File");
287 wxMenu
*thread_menu
= new wxMenu
;
288 thread_menu
->Append(TEST_START_THREAD
, "&Start a new thread\tCtrl-N");
289 thread_menu
->Append(TEST_START_THREADS
, "Start &many threads at once");
290 thread_menu
->Append(TEST_STOP_THREAD
, "S&top a running thread\tCtrl-S");
291 thread_menu
->AppendSeparator();
292 thread_menu
->Append(TEST_PAUSE_THREAD
, "&Pause a running thread\tCtrl-P");
293 thread_menu
->Append(TEST_RESUME_THREAD
, "&Resume suspended thread\tCtrl-R");
294 thread_menu
->AppendSeparator();
295 thread_menu
->Append(TEST_START_WORKER
, "Start &worker thread\tCtrl-W");
297 menu_bar
->Append(thread_menu
, "&Thread");
298 frame
->SetMenuBar(menu_bar
);
308 // My frame constructor
309 MyFrame::MyFrame(wxFrame
*frame
, const wxString
& title
,
310 int x
, int y
, int w
, int h
)
311 : wxFrame(frame
, -1, title
, wxPoint(x
, y
), wxSize(w
, h
))
313 m_nRunning
= m_nCount
= 0;
317 m_txtctrl
= new wxTextCtrl(this, -1, "", wxPoint(0, 0), wxSize(0, 0),
318 wxTE_MULTILINE
| wxTE_READONLY
);
322 MyThread
*MyFrame::CreateThread()
324 MyThread
*thread
= new MyThread(this);
326 if ( thread
->Create() != wxTHREAD_NO_ERROR
)
328 wxLogError("Can't create thread!");
331 wxCriticalSectionLocker
enter(wxGetApp().m_critsect
);
332 wxGetApp().m_threads
.Add(thread
);
337 void MyFrame::OnStartThreads(wxCommandEvent
& WXUNUSED(event
) )
339 static long s_num
= 10;
341 s_num
= wxGetNumberFromUser("How many threads to start: ", "",
342 "wxThread sample", s_num
, 1, 10000, this);
350 size_t count
= (size_t)s_num
, n
;
352 wxArrayThread threads
;
354 // first create them all...
355 for ( n
= 0; n
< count
; n
++ )
357 wxThread
*thr
= CreateThread();
359 // we want to show the effect of SetPriority(): the first thread will
360 // have the lowest priority, the second - the highest, all the rest
363 thr
->SetPriority(WXTHREAD_MIN_PRIORITY
);
365 thr
->SetPriority(WXTHREAD_MAX_PRIORITY
);
367 thr
->SetPriority(WXTHREAD_DEFAULT_PRIORITY
);
373 msg
.Printf("%d new threads created.", count
);
374 SetStatusText(msg
, 1);
376 // ...and then start them
377 for ( n
= 0; n
< count
; n
++ )
383 void MyFrame::OnStartThread(wxCommandEvent
& WXUNUSED(event
) )
385 MyThread
*thread
= CreateThread();
387 if ( thread
->Run() != wxTHREAD_NO_ERROR
)
389 wxLogError("Can't start thread!");
392 SetStatusText("New thread started.", 1);
395 void MyFrame::OnStopThread(wxCommandEvent
& WXUNUSED(event
) )
397 // stop the last thread
398 if ( wxGetApp().m_threads
.IsEmpty() )
400 wxLogError("No thread to stop!");
404 wxGetApp().m_critsect
.Enter();
406 wxThread
*thread
= wxGetApp().m_threads
.Last();
408 // it's important to leave critical section before calling Delete()
409 // because delete will (implicitly) call OnExit() which also tries
410 // to enter the same crit section - would dead lock.
411 wxGetApp().m_critsect
.Leave();
415 SetStatusText("Thread stopped.", 1);
419 void MyFrame::OnResumeThread(wxCommandEvent
& WXUNUSED(event
) )
421 wxCriticalSectionLocker
enter(wxGetApp().m_critsect
);
423 // resume first suspended thread
424 size_t n
= 0, count
= wxGetApp().m_threads
.Count();
425 while ( n
< count
&& !wxGetApp().m_threads
[n
]->IsPaused() )
430 wxLogError("No thread to resume!");
434 wxGetApp().m_threads
[n
]->Resume();
436 SetStatusText("Thread resumed.", 1);
440 void MyFrame::OnPauseThread(wxCommandEvent
& WXUNUSED(event
) )
442 wxCriticalSectionLocker
enter(wxGetApp().m_critsect
);
444 // pause last running thread
445 int n
= wxGetApp().m_threads
.Count() - 1;
446 while ( n
>= 0 && !wxGetApp().m_threads
[n
]->IsRunning() )
451 wxLogError("No thread to pause!");
455 wxGetApp().m_threads
[n
]->Pause();
457 SetStatusText("Thread paused.", 1);
461 // set the frame title indicating the current number of threads
462 void MyFrame::OnIdle(wxIdleEvent
&event
)
464 // update the counts of running/total threads
466 nCount
= wxGetApp().m_threads
.Count();
467 for ( size_t n
= 0; n
< nCount
; n
++ )
469 if ( wxGetApp().m_threads
[n
]->IsRunning() )
473 if ( nCount
!= m_nCount
|| nRunning
!= m_nRunning
)
475 m_nRunning
= nRunning
;
478 wxLogStatus(this, "%u threads total, %u running.", nCount
, nRunning
);
480 //else: avoid flicker - don't print anything
483 void MyFrame::OnQuit(wxCommandEvent
& WXUNUSED(event
) )
485 size_t count
= wxGetApp().m_threads
.Count();
486 for ( size_t i
= 0; i
< count
; i
++ )
488 wxGetApp().m_threads
[0]->Delete();
494 void MyFrame::OnAbout(wxCommandEvent
& WXUNUSED(event
) )
496 wxMessageDialog
dialog(this, "wxWindows multithreaded application sample\n"
497 "(c) 1998 Julian Smart, Guilhem Lavaux\n"
498 "(c) 1999 Vadim Zeitlin",
499 "About wxThread sample",
500 wxOK
| wxICON_INFORMATION
);
505 void MyFrame::OnClear(wxCommandEvent
& WXUNUSED(event
))
510 void MyFrame::OnStartWorker(wxCommandEvent
& WXUNUSED(event
))
512 MyWorkerThread
*thread
= new MyWorkerThread(this);
514 if ( thread
->Create() != wxTHREAD_NO_ERROR
)
516 wxLogError("Can't create thread!");
522 void MyFrame::OnWorkerEvent(wxCommandEvent
& WXUNUSED(event
))
524 WriteText( "Got message from worker thread\n" );