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"
41 #include "wx/progdlg.h"
44 WX_DEFINE_ARRAY(wxThread
*, wxArrayThread
);
46 // Define a new application type
47 class MyApp
: public wxApp
50 virtual bool OnInit();
53 // all the threads currently alive - as soon as the thread terminates, it's
54 // removed from the array
55 wxArrayThread m_threads
;
57 // crit section protects access to all of the arrays below
58 wxCriticalSection m_critsect
;
61 // Create a new application object
64 // Define a new frame type
65 class MyFrame
: public wxFrame
69 MyFrame(wxFrame
*frame
, const wxString
& title
, int x
, int y
, int w
, int h
);
72 void WriteText(const wxString
& text
) { m_txtctrl
->WriteText(text
); }
74 // accessors for MyWorkerThread (called in its context!)
78 void OnQuit(wxCommandEvent
& event
);
79 void OnAbout(wxCommandEvent
& event
);
80 void OnClear(wxCommandEvent
& event
);
82 void OnStartThread(wxCommandEvent
& event
);
83 void OnStartThreads(wxCommandEvent
& event
);
84 void OnStopThread(wxCommandEvent
& event
);
85 void OnPauseThread(wxCommandEvent
& event
);
86 void OnResumeThread(wxCommandEvent
& event
);
88 void OnStartWorker(wxCommandEvent
& event
);
89 void OnWorkerEvent(wxCommandEvent
& event
);
90 void OnUpdateWorker(wxUpdateUIEvent
& event
);
92 void OnIdle(wxIdleEvent
&event
);
95 // helper function - creates a new thread (but doesn't run it)
96 MyThread
*CreateThread();
98 // just some place to put our messages in
99 wxTextCtrl
*m_txtctrl
;
101 // remember the number of running threads and total number of threads
102 size_t m_nRunning
, m_nCount
;
104 // the progress dialog which we show while worker thread is running
105 wxProgressDialog
*m_dlgProgress
;
107 // was the worker thread cancelled by user?
110 // protects m_cancelled
111 wxCriticalSection m_critsectWork
;
113 DECLARE_EVENT_TABLE()
116 // ID for the menu commands
123 TEST_START_THREAD
= 201,
129 WORKER_EVENT
// this one gets sent from the worker thread
132 //--------------------------------------------------
134 //--------------------------------------------------
136 class MyThread
: public wxThread
139 MyThread(MyFrame
*frame
);
141 // thread execution starts here
142 virtual void *Entry();
144 // called when the thread exits - whether it terminates normally or is
145 // stopped with Delete() (but not when it is Kill()ed!)
146 virtual void OnExit();
148 // write something to the text control
149 void WriteText(const wxString
& text
);
156 MyThread::MyThread(MyFrame
*frame
)
163 void MyThread::WriteText(const wxString
& text
)
167 // before doing any GUI calls we must ensure that this thread is the only
173 m_frame
->WriteText(msg
);
178 void MyThread::OnExit()
180 wxCriticalSectionLocker
locker(wxGetApp().m_critsect
);
182 wxGetApp().m_threads
.Remove(this);
185 void *MyThread::Entry()
189 text
.Printf("Thread 0x%x started (priority = %d).\n",
190 GetId(), GetPriority());
192 // wxLogMessage(text); -- test wxLog thread safeness
194 for ( m_count
= 0; m_count
< 10; m_count
++ )
196 // check if we were asked to exit
200 text
.Printf("[%u] Thread 0x%x here.\n", m_count
, GetId());
203 // wxSleep() can't be called from non-GUI thread!
204 wxThread::Sleep(1000);
207 text
.Printf("Thread 0x%x finished.\n", GetId());
209 // wxLogMessage(text); -- test wxLog thread safeness
214 //--------------------------------------------------
216 //--------------------------------------------------
218 class MyWorkerThread
: public wxThread
221 MyWorkerThread(MyFrame
*frame
);
223 // thread execution starts here
224 virtual void *Entry();
226 // called when the thread exits - whether it terminates normally or is
227 // stopped with Delete() (but not when it is Kill()ed!)
228 virtual void OnExit();
235 MyWorkerThread::MyWorkerThread(MyFrame
*frame
)
242 void MyWorkerThread::OnExit()
246 void *MyWorkerThread::Entry()
248 for ( m_count
= 0; !m_frame
->Cancelled() && (m_count
< 100); m_count
++ )
250 // check if we were asked to exit
255 text
.Printf("[%u] Thread 0x%x here!!", m_count
, GetId());
257 // create any type of command event here
258 wxCommandEvent
event( wxEVT_COMMAND_MENU_SELECTED
, WORKER_EVENT
);
259 event
.SetInt( m_count
);
260 event
.SetString( text
);
262 // send in a thread-safe way
263 wxPostEvent( m_frame
, event
);
266 // m_frame->AddPendingEvent( event );
268 // wxSleep() can't be called from non-main thread!
269 wxThread::Sleep(200);
272 wxCommandEvent
event( wxEVT_COMMAND_MENU_SELECTED
, WORKER_EVENT
);
273 event
.SetInt(-1); // that's all
274 wxPostEvent( m_frame
, event
);
279 //--------------------------------------------------
281 //--------------------------------------------------
283 BEGIN_EVENT_TABLE(MyFrame
, wxFrame
)
284 EVT_MENU(TEST_QUIT
, MyFrame::OnQuit
)
285 EVT_MENU(TEST_ABOUT
, MyFrame::OnAbout
)
286 EVT_MENU(TEST_CLEAR
, MyFrame::OnClear
)
287 EVT_MENU(TEST_START_THREAD
, MyFrame::OnStartThread
)
288 EVT_MENU(TEST_START_THREADS
, MyFrame::OnStartThreads
)
289 EVT_MENU(TEST_STOP_THREAD
, MyFrame::OnStopThread
)
290 EVT_MENU(TEST_PAUSE_THREAD
, MyFrame::OnPauseThread
)
291 EVT_MENU(TEST_RESUME_THREAD
, MyFrame::OnResumeThread
)
293 EVT_UPDATE_UI(TEST_START_WORKER
, MyFrame::OnUpdateWorker
)
294 EVT_MENU(TEST_START_WORKER
, MyFrame::OnStartWorker
)
295 EVT_MENU(WORKER_EVENT
, MyFrame::OnWorkerEvent
)
297 EVT_IDLE(MyFrame::OnIdle
)
300 // `Main program' equivalent, creating windows and returning main app frame
303 // Create the main frame window
304 MyFrame
*frame
= new MyFrame((wxFrame
*)NULL
, "wxWindows threads sample",
308 wxMenu
*file_menu
= new wxMenu
;
310 file_menu
->Append(TEST_CLEAR
, "&Clear log\tCtrl-L");
311 file_menu
->AppendSeparator();
312 file_menu
->Append(TEST_ABOUT
, "&About");
313 file_menu
->AppendSeparator();
314 file_menu
->Append(TEST_QUIT
, "E&xit\tAlt-X");
315 wxMenuBar
*menu_bar
= new wxMenuBar
;
316 menu_bar
->Append(file_menu
, "&File");
318 wxMenu
*thread_menu
= new wxMenu
;
319 thread_menu
->Append(TEST_START_THREAD
, "&Start a new thread\tCtrl-N");
320 thread_menu
->Append(TEST_START_THREADS
, "Start &many threads at once");
321 thread_menu
->Append(TEST_STOP_THREAD
, "S&top a running thread\tCtrl-S");
322 thread_menu
->AppendSeparator();
323 thread_menu
->Append(TEST_PAUSE_THREAD
, "&Pause a running thread\tCtrl-P");
324 thread_menu
->Append(TEST_RESUME_THREAD
, "&Resume suspended thread\tCtrl-R");
325 thread_menu
->AppendSeparator();
326 thread_menu
->Append(TEST_START_WORKER
, "Start &worker thread\tCtrl-W");
328 menu_bar
->Append(thread_menu
, "&Thread");
329 frame
->SetMenuBar(menu_bar
);
339 // My frame constructor
340 MyFrame::MyFrame(wxFrame
*frame
, const wxString
& title
,
341 int x
, int y
, int w
, int h
)
342 : wxFrame(frame
, -1, title
, wxPoint(x
, y
), wxSize(w
, h
))
344 m_nRunning
= m_nCount
= 0;
346 m_dlgProgress
= (wxProgressDialog
*)NULL
;
350 m_txtctrl
= new wxTextCtrl(this, -1, "", wxPoint(0, 0), wxSize(0, 0),
351 wxTE_MULTILINE
| wxTE_READONLY
);
355 MyThread
*MyFrame::CreateThread()
357 MyThread
*thread
= new MyThread(this);
359 if ( thread
->Create() != wxTHREAD_NO_ERROR
)
361 wxLogError("Can't create thread!");
364 wxCriticalSectionLocker
enter(wxGetApp().m_critsect
);
365 wxGetApp().m_threads
.Add(thread
);
370 void MyFrame::OnStartThreads(wxCommandEvent
& WXUNUSED(event
) )
372 static long s_num
= 10;
374 s_num
= wxGetNumberFromUser("How many threads to start: ", "",
375 "wxThread sample", s_num
, 1, 10000, this);
383 size_t count
= (size_t)s_num
, n
;
385 wxArrayThread threads
;
387 // first create them all...
388 for ( n
= 0; n
< count
; n
++ )
390 wxThread
*thr
= CreateThread();
392 // we want to show the effect of SetPriority(): the first thread will
393 // have the lowest priority, the second - the highest, all the rest
396 thr
->SetPriority(WXTHREAD_MIN_PRIORITY
);
398 thr
->SetPriority(WXTHREAD_MAX_PRIORITY
);
400 thr
->SetPriority(WXTHREAD_DEFAULT_PRIORITY
);
406 msg
.Printf("%d new threads created.", count
);
407 SetStatusText(msg
, 1);
409 // ...and then start them
410 for ( n
= 0; n
< count
; n
++ )
416 void MyFrame::OnStartThread(wxCommandEvent
& WXUNUSED(event
) )
418 MyThread
*thread
= CreateThread();
420 if ( thread
->Run() != wxTHREAD_NO_ERROR
)
422 wxLogError("Can't start thread!");
425 SetStatusText("New thread started.", 1);
428 void MyFrame::OnStopThread(wxCommandEvent
& WXUNUSED(event
) )
430 // stop the last thread
431 if ( wxGetApp().m_threads
.IsEmpty() )
433 wxLogError("No thread to stop!");
437 wxGetApp().m_critsect
.Enter();
439 wxThread
*thread
= wxGetApp().m_threads
.Last();
441 // it's important to leave critical section before calling Delete()
442 // because delete will (implicitly) call OnExit() which also tries
443 // to enter the same crit section - would dead lock.
444 wxGetApp().m_critsect
.Leave();
448 SetStatusText("Thread stopped.", 1);
452 void MyFrame::OnResumeThread(wxCommandEvent
& WXUNUSED(event
) )
454 wxCriticalSectionLocker
enter(wxGetApp().m_critsect
);
456 // resume first suspended thread
457 size_t n
= 0, count
= wxGetApp().m_threads
.Count();
458 while ( n
< count
&& !wxGetApp().m_threads
[n
]->IsPaused() )
463 wxLogError("No thread to resume!");
467 wxGetApp().m_threads
[n
]->Resume();
469 SetStatusText("Thread resumed.", 1);
473 void MyFrame::OnPauseThread(wxCommandEvent
& WXUNUSED(event
) )
475 wxCriticalSectionLocker
enter(wxGetApp().m_critsect
);
477 // pause last running thread
478 int n
= wxGetApp().m_threads
.Count() - 1;
479 while ( n
>= 0 && !wxGetApp().m_threads
[n
]->IsRunning() )
484 wxLogError("No thread to pause!");
488 wxGetApp().m_threads
[n
]->Pause();
490 SetStatusText("Thread paused.", 1);
494 // set the frame title indicating the current number of threads
495 void MyFrame::OnIdle(wxIdleEvent
&event
)
497 // update the counts of running/total threads
499 nCount
= wxGetApp().m_threads
.Count();
500 for ( size_t n
= 0; n
< nCount
; n
++ )
502 if ( wxGetApp().m_threads
[n
]->IsRunning() )
506 if ( nCount
!= m_nCount
|| nRunning
!= m_nRunning
)
508 m_nRunning
= nRunning
;
511 wxLogStatus(this, "%u threads total, %u running.", nCount
, nRunning
);
513 //else: avoid flicker - don't print anything
516 void MyFrame::OnQuit(wxCommandEvent
& WXUNUSED(event
) )
518 size_t count
= wxGetApp().m_threads
.Count();
519 for ( size_t i
= 0; i
< count
; i
++ )
521 wxGetApp().m_threads
[0]->Delete();
527 void MyFrame::OnAbout(wxCommandEvent
& WXUNUSED(event
) )
529 wxMessageDialog
dialog(this, "wxWindows multithreaded application sample\n"
530 "(c) 1998 Julian Smart, Guilhem Lavaux\n"
531 "(c) 1999 Vadim Zeitlin\n"
532 "(c) 2000 Robert Roebling",
533 "About wxThread sample",
534 wxOK
| wxICON_INFORMATION
);
539 void MyFrame::OnClear(wxCommandEvent
& WXUNUSED(event
))
544 void MyFrame::OnUpdateWorker(wxUpdateUIEvent
& event
)
546 event
.Enable( m_dlgProgress
== NULL
);
549 void MyFrame::OnStartWorker(wxCommandEvent
& WXUNUSED(event
))
551 MyWorkerThread
*thread
= new MyWorkerThread(this);
553 if ( thread
->Create() != wxTHREAD_NO_ERROR
)
555 wxLogError("Can't create thread!");
558 m_dlgProgress
= new wxProgressDialog
561 "Wait until the thread terminates or press [Cancel]",
567 wxPD_ESTIMATED_TIME
|
571 // thread is not running yet, no need for crit sect
577 void MyFrame::OnWorkerEvent(wxCommandEvent
& event
)
580 WriteText( "Got message from worker thread: " );
581 WriteText( event
.GetString() );
584 int n
= event
.GetInt();
587 m_dlgProgress
->Destroy();
588 m_dlgProgress
= (wxProgressDialog
*)NULL
;
590 // the dialog is aborted because the event came from another thread, so
591 // we may need to wake up the main event loop for the dialog to be
597 if ( !m_dlgProgress
->Update(n
) )
599 wxCriticalSectionLocker
lock(m_critsectWork
);
607 bool MyFrame::Cancelled()
609 wxCriticalSectionLocker
lock(m_critsectWork
);