1 /////////////////////////////////////////////////////////////////////////////
3 // Purpose: wxWindows thread sample
4 // Author: Guilhem Lavaux, Vadim Zeitlin
8 // Copyright: (c) 1998-2002 wxWindows team
9 // Licence: wxWindows license
10 /////////////////////////////////////////////////////////////////////////////
12 // For compilers that support precompilation, includes "wx/wx.h".
13 #include "wx/wxprec.h"
24 #error "This sample requires thread support!"
25 #endif // wxUSE_THREADS
27 #include "wx/thread.h"
28 #include "wx/dynarray.h"
31 #include "wx/progdlg.h"
33 // define this to use wxExecute in the exec tests, otherwise just use system
37 #define EXEC(cmd) wxExecute((cmd), wxEXEC_SYNC)
39 #define EXEC(cmd) system(cmd)
43 WX_DEFINE_ARRAY(wxThread
*, wxArrayThread
);
45 // Define a new application type
46 class MyApp
: public wxApp
52 virtual bool OnInit();
55 // all the threads currently alive - as soon as the thread terminates, it's
56 // removed from the array
57 wxArrayThread m_threads
;
59 // crit section protects access to all of the arrays below
60 wxCriticalSection m_critsect
;
62 // the (mutex, condition) pair used to wait for the threads to exit, see
64 wxMutex m_mutexAllDone
;
65 wxCondition m_condAllDone
;
67 // the last exiting thread should signal m_condAllDone if this is true
68 // (protected by the same m_critsect)
69 bool m_waitingUntilAllDone
;
72 // Create a new application object
75 // Define a new frame type
76 class MyFrame
: public wxFrame
80 MyFrame(wxFrame
*frame
, const wxString
& title
, int x
, int y
, int w
, int h
);
83 void WriteText(const wxString
& text
) { m_txtctrl
->WriteText(text
); }
85 // accessors for MyWorkerThread (called in its context!)
90 void OnQuit(wxCommandEvent
& event
);
91 void OnClear(wxCommandEvent
& event
);
93 void OnStartThread(wxCommandEvent
& event
);
94 void OnStartThreads(wxCommandEvent
& event
);
95 void OnStopThread(wxCommandEvent
& event
);
96 void OnPauseThread(wxCommandEvent
& event
);
97 void OnResumeThread(wxCommandEvent
& event
);
99 void OnStartWorker(wxCommandEvent
& event
);
100 void OnWorkerEvent(wxCommandEvent
& event
);
101 void OnUpdateWorker(wxUpdateUIEvent
& event
);
103 void OnExecMain(wxCommandEvent
& event
);
104 void OnExecThread(wxCommandEvent
& event
);
106 void OnShowCPUs(wxCommandEvent
& event
);
107 void OnAbout(wxCommandEvent
& event
);
109 void OnIdle(wxIdleEvent
&event
);
112 // helper function - creates a new thread (but doesn't run it)
113 MyThread
*CreateThread();
115 // just some place to put our messages in
116 wxTextCtrl
*m_txtctrl
;
118 // remember the number of running threads and total number of threads
119 size_t m_nRunning
, m_nCount
;
121 // the progress dialog which we show while worker thread is running
122 wxProgressDialog
*m_dlgProgress
;
124 // was the worker thread cancelled by user?
127 // protects m_cancelled
128 wxCriticalSection m_critsectWork
;
130 DECLARE_EVENT_TABLE()
133 // ID for the menu commands
139 THREAD_START_THREAD
= 201,
140 THREAD_START_THREADS
,
143 THREAD_RESUME_THREAD
,
152 WORKER_EVENT
// this one gets sent from the worker thread
155 // ----------------------------------------------------------------------------
157 // ----------------------------------------------------------------------------
159 class MyThread
: public wxThread
162 MyThread(MyFrame
*frame
);
164 // thread execution starts here
165 virtual void *Entry();
167 // called when the thread exits - whether it terminates normally or is
168 // stopped with Delete() (but not when it is Kill()ed!)
169 virtual void OnExit();
171 // write something to the text control
172 void WriteText(const wxString
& text
);
179 MyThread::MyThread(MyFrame
*frame
)
186 void MyThread::WriteText(const wxString
& text
)
190 // before doing any GUI calls we must ensure that this thread is the only
196 m_frame
->WriteText(msg
);
201 void MyThread::OnExit()
203 wxCriticalSectionLocker
locker(wxGetApp().m_critsect
);
205 wxArrayThread
& threads
= wxGetApp().m_threads
;
206 threads
.Remove(this);
208 if ( threads
.IsEmpty() )
210 // signal the main thread that there are no more threads left if it is
212 if ( wxGetApp().m_waitingUntilAllDone
)
214 wxGetApp().m_waitingUntilAllDone
= FALSE
;
216 wxMutexLocker
lock(wxGetApp().m_mutexAllDone
);
217 wxGetApp().m_condAllDone
.Signal();
222 void *MyThread::Entry()
226 text
.Printf(wxT("Thread 0x%x started (priority = %u).\n"),
227 GetId(), GetPriority());
229 // wxLogMessage(text); -- test wxLog thread safeness
231 for ( m_count
= 0; m_count
< 10; m_count
++ )
233 // check if we were asked to exit
237 text
.Printf(wxT("[%u] Thread 0x%x here.\n"), m_count
, GetId());
240 // wxSleep() can't be called from non-GUI thread!
241 wxThread::Sleep(1000);
244 text
.Printf(wxT("Thread 0x%x finished.\n"), GetId());
246 // wxLogMessage(text); -- test wxLog thread safeness
251 // ----------------------------------------------------------------------------
253 // ----------------------------------------------------------------------------
255 class MyWorkerThread
: public wxThread
258 MyWorkerThread(MyFrame
*frame
);
260 // thread execution starts here
261 virtual void *Entry();
263 // called when the thread exits - whether it terminates normally or is
264 // stopped with Delete() (but not when it is Kill()ed!)
265 virtual void OnExit();
272 MyWorkerThread::MyWorkerThread(MyFrame
*frame
)
279 void MyWorkerThread::OnExit()
283 void *MyWorkerThread::Entry()
285 for ( m_count
= 0; !m_frame
->Cancelled() && (m_count
< 100); m_count
++ )
287 // check if we were asked to exit
291 // create any type of command event here
292 wxCommandEvent
event( wxEVT_COMMAND_MENU_SELECTED
, WORKER_EVENT
);
293 event
.SetInt( m_count
);
295 // send in a thread-safe way
296 wxPostEvent( m_frame
, event
);
298 // wxSleep() can't be called from non-main thread!
299 wxThread::Sleep(200);
302 wxCommandEvent
event( wxEVT_COMMAND_MENU_SELECTED
, WORKER_EVENT
);
303 event
.SetInt(-1); // that's all
304 wxPostEvent( m_frame
, event
);
309 // ----------------------------------------------------------------------------
310 // a thread which simply calls wxExecute
311 // ----------------------------------------------------------------------------
313 class MyExecThread
: public wxThread
316 MyExecThread(const wxChar
*command
) : wxThread(wxTHREAD_JOINABLE
),
322 virtual ExitCode
Entry()
324 return (ExitCode
)EXEC(m_command
);
331 // ----------------------------------------------------------------------------
333 // ----------------------------------------------------------------------------
335 BEGIN_EVENT_TABLE(MyFrame
, wxFrame
)
336 EVT_MENU(THREAD_QUIT
, MyFrame::OnQuit
)
337 EVT_MENU(THREAD_CLEAR
, MyFrame::OnClear
)
338 EVT_MENU(THREAD_START_THREAD
, MyFrame::OnStartThread
)
339 EVT_MENU(THREAD_START_THREADS
, MyFrame::OnStartThreads
)
340 EVT_MENU(THREAD_STOP_THREAD
, MyFrame::OnStopThread
)
341 EVT_MENU(THREAD_PAUSE_THREAD
, MyFrame::OnPauseThread
)
342 EVT_MENU(THREAD_RESUME_THREAD
, MyFrame::OnResumeThread
)
344 EVT_MENU(THREAD_EXEC_MAIN
, MyFrame::OnExecMain
)
345 EVT_MENU(THREAD_EXEC_THREAD
, MyFrame::OnExecThread
)
347 EVT_MENU(THREAD_SHOWCPUS
, MyFrame::OnShowCPUs
)
348 EVT_MENU(THREAD_ABOUT
, MyFrame::OnAbout
)
350 EVT_UPDATE_UI(THREAD_START_WORKER
, MyFrame::OnUpdateWorker
)
351 EVT_MENU(THREAD_START_WORKER
, MyFrame::OnStartWorker
)
352 EVT_MENU(WORKER_EVENT
, MyFrame::OnWorkerEvent
)
354 EVT_IDLE(MyFrame::OnIdle
)
358 : m_condAllDone(m_mutexAllDone
)
360 // the mutex associated with a condition must be initially locked, it will
361 // only be unlocked when we call Wait()
362 m_mutexAllDone
.Lock();
364 m_waitingUntilAllDone
= FALSE
;
369 // the mutex must be unlocked before being destroyed
370 m_mutexAllDone
.Unlock();
373 // `Main program' equivalent, creating windows and returning main app frame
376 // uncomment this to get some debugging messages from the trace code
377 // on the console (or just set WXTRACE env variable to include "thread")
378 //wxLog::AddTraceMask("thread");
380 // Create the main frame window
381 MyFrame
*frame
= new MyFrame((wxFrame
*)NULL
, "wxWindows threads sample",
385 wxMenuBar
*menuBar
= new wxMenuBar
;
387 wxMenu
*menuFile
= new wxMenu
;
388 menuFile
->Append(THREAD_CLEAR
, "&Clear log\tCtrl-L");
389 menuFile
->AppendSeparator();
390 menuFile
->Append(THREAD_QUIT
, "E&xit\tAlt-X");
391 menuBar
->Append(menuFile
, "&File");
393 wxMenu
*menuThread
= new wxMenu
;
394 menuThread
->Append(THREAD_START_THREAD
, "&Start a new thread\tCtrl-N");
395 menuThread
->Append(THREAD_START_THREADS
, "Start &many threads at once");
396 menuThread
->Append(THREAD_STOP_THREAD
, "S&top a running thread\tCtrl-S");
397 menuThread
->AppendSeparator();
398 menuThread
->Append(THREAD_PAUSE_THREAD
, "&Pause a running thread\tCtrl-P");
399 menuThread
->Append(THREAD_RESUME_THREAD
, "&Resume suspended thread\tCtrl-R");
400 menuThread
->AppendSeparator();
401 menuThread
->Append(THREAD_START_WORKER
, "Start &worker thread\tCtrl-W");
402 menuBar
->Append(menuThread
, "&Thread");
404 wxMenu
*menuExec
= new wxMenu
;
405 menuExec
->Append(THREAD_EXEC_MAIN
, "&Launch a program from main thread\tF5");
406 menuExec
->Append(THREAD_EXEC_THREAD
, "L&aunch a program from a thread\tCtrl-F5");
407 menuBar
->Append(menuExec
, "&Execute");
409 wxMenu
*menuHelp
= new wxMenu
;
410 menuHelp
->Append(THREAD_SHOWCPUS
, "&Show CPU count");
411 menuHelp
->AppendSeparator();
412 menuHelp
->Append(THREAD_ABOUT
, "&About...");
413 menuBar
->Append(menuHelp
, "&Help");
415 frame
->SetMenuBar(menuBar
);
425 // My frame constructor
426 MyFrame::MyFrame(wxFrame
*frame
, const wxString
& title
,
427 int x
, int y
, int w
, int h
)
428 : wxFrame(frame
, -1, title
, wxPoint(x
, y
), wxSize(w
, h
))
430 m_nRunning
= m_nCount
= 0;
432 m_dlgProgress
= (wxProgressDialog
*)NULL
;
436 m_txtctrl
= new wxTextCtrl(this, -1, "", wxPoint(0, 0), wxSize(0, 0),
437 wxTE_MULTILINE
| wxTE_READONLY
);
441 MyThread
*MyFrame::CreateThread()
443 MyThread
*thread
= new MyThread(this);
445 if ( thread
->Create() != wxTHREAD_NO_ERROR
)
447 wxLogError(wxT("Can't create thread!"));
450 wxCriticalSectionLocker
enter(wxGetApp().m_critsect
);
451 wxGetApp().m_threads
.Add(thread
);
456 void MyFrame::OnStartThreads(wxCommandEvent
& WXUNUSED(event
) )
458 static long s_num
= 10;
460 s_num
= wxGetNumberFromUser("How many threads to start: ", "",
461 "wxThread sample", s_num
, 1, 10000, this);
469 size_t count
= (size_t)s_num
, n
;
471 wxArrayThread threads
;
473 // first create them all...
474 for ( n
= 0; n
< count
; n
++ )
476 wxThread
*thr
= CreateThread();
478 // we want to show the effect of SetPriority(): the first thread will
479 // have the lowest priority, the second - the highest, all the rest
482 thr
->SetPriority(WXTHREAD_MIN_PRIORITY
);
484 thr
->SetPriority(WXTHREAD_MAX_PRIORITY
);
486 thr
->SetPriority(WXTHREAD_DEFAULT_PRIORITY
);
492 msg
.Printf(wxT("%d new threads created."), count
);
493 SetStatusText(msg
, 1);
495 // ...and then start them
496 for ( n
= 0; n
< count
; n
++ )
502 void MyFrame::OnStartThread(wxCommandEvent
& WXUNUSED(event
) )
504 MyThread
*thread
= CreateThread();
506 if ( thread
->Run() != wxTHREAD_NO_ERROR
)
508 wxLogError(wxT("Can't start thread!"));
511 SetStatusText("New thread started.", 1);
514 void MyFrame::OnStopThread(wxCommandEvent
& WXUNUSED(event
) )
516 wxGetApp().m_critsect
.Enter();
518 // stop the last thread
519 if ( wxGetApp().m_threads
.IsEmpty() )
521 wxLogError(wxT("No thread to stop!"));
523 wxGetApp().m_critsect
.Leave();
527 wxThread
*thread
= wxGetApp().m_threads
.Last();
529 // it's important to leave critical section before calling Delete()
530 // because delete will (implicitly) call OnExit() which also tries
531 // to enter the same crit section - would dead lock.
532 wxGetApp().m_critsect
.Leave();
536 SetStatusText("Thread stopped.", 1);
540 void MyFrame::OnResumeThread(wxCommandEvent
& WXUNUSED(event
) )
542 wxCriticalSectionLocker
enter(wxGetApp().m_critsect
);
544 // resume first suspended thread
545 size_t n
= 0, count
= wxGetApp().m_threads
.Count();
546 while ( n
< count
&& !wxGetApp().m_threads
[n
]->IsPaused() )
551 wxLogError(wxT("No thread to resume!"));
555 wxGetApp().m_threads
[n
]->Resume();
557 SetStatusText("Thread resumed.", 1);
561 void MyFrame::OnPauseThread(wxCommandEvent
& WXUNUSED(event
) )
563 wxCriticalSectionLocker
enter(wxGetApp().m_critsect
);
565 // pause last running thread
566 int n
= wxGetApp().m_threads
.Count() - 1;
567 while ( n
>= 0 && !wxGetApp().m_threads
[n
]->IsRunning() )
572 wxLogError(wxT("No thread to pause!"));
576 wxGetApp().m_threads
[n
]->Pause();
578 SetStatusText("Thread paused.", 1);
582 // set the frame title indicating the current number of threads
583 void MyFrame::OnIdle(wxIdleEvent
&event
)
585 wxCriticalSectionLocker
enter(wxGetApp().m_critsect
);
587 // update the counts of running/total threads
589 nCount
= wxGetApp().m_threads
.Count();
590 for ( size_t n
= 0; n
< nCount
; n
++ )
592 if ( wxGetApp().m_threads
[n
]->IsRunning() )
596 if ( nCount
!= m_nCount
|| nRunning
!= m_nRunning
)
598 m_nRunning
= nRunning
;
601 wxLogStatus(this, wxT("%u threads total, %u running."), nCount
, nRunning
);
603 //else: avoid flicker - don't print anything
606 void MyFrame::OnQuit(wxCommandEvent
& WXUNUSED(event
) )
608 // NB: although the OS will terminate all the threads anyhow when the main
609 // one exits, it's good practice to do it ourselves -- even if it's not
610 // completely trivial in this example
612 // tell all the threads to terminate: note that they can't terminate while
613 // we're deleting them because they will block in their OnExit() -- this is
614 // important as otherwise we might access invalid array elements
616 wxGetApp().m_critsect
.Enter();
618 // check if we have any threads running first
619 const wxArrayThread
& threads
= wxGetApp().m_threads
;
620 size_t count
= threads
.GetCount();
624 // we do, ask them to stop
625 for ( size_t n
= 0; n
< count
; n
++ )
627 threads
[n
]->Delete();
630 // set the flag for MyThread::OnExit()
631 wxGetApp().m_waitingUntilAllDone
= TRUE
;
634 wxGetApp().m_critsect
.Leave();
638 // now wait for them to really terminate but leave the GUI mutex
639 // before doing it as otherwise we might dead lock
642 wxGetApp().m_condAllDone
.Wait();
646 //else: no threads to terminate, no condition to wait for
652 void MyFrame::OnExecMain(wxCommandEvent
& WXUNUSED(event
))
654 wxLogMessage(wxT("The exit code from the main program is %ld"),
655 EXEC("/bin/echo \"main program\""));
658 void MyFrame::OnExecThread(wxCommandEvent
& WXUNUSED(event
))
660 MyExecThread
thread(wxT("/bin/echo \"child thread\""));
663 wxLogMessage(wxT("The exit code from a child thread is %ld"),
664 (long)thread
.Wait());
667 void MyFrame::OnShowCPUs(wxCommandEvent
& WXUNUSED(event
))
671 int nCPUs
= wxThread::GetCPUCount();
675 msg
= "Unknown number of CPUs";
679 msg
= "WARNING: you're running without any CPUs!";
683 msg
= "This system only has one CPU.";
687 msg
.Printf(wxT("This system has %d CPUs"), nCPUs
);
693 void MyFrame::OnAbout(wxCommandEvent
& WXUNUSED(event
) )
695 wxMessageDialog
dialog(this, "wxWindows multithreaded application sample\n"
696 "(c) 1998 Julian Smart, Guilhem Lavaux\n"
697 "(c) 1999 Vadim Zeitlin\n"
698 "(c) 2000 Robert Roebling",
699 "About wxThread sample",
700 wxOK
| wxICON_INFORMATION
);
705 void MyFrame::OnClear(wxCommandEvent
& WXUNUSED(event
))
710 void MyFrame::OnUpdateWorker(wxUpdateUIEvent
& event
)
712 event
.Enable( m_dlgProgress
== NULL
);
715 void MyFrame::OnStartWorker(wxCommandEvent
& WXUNUSED(event
))
717 MyWorkerThread
*thread
= new MyWorkerThread(this);
719 if ( thread
->Create() != wxTHREAD_NO_ERROR
)
721 wxLogError(wxT("Can't create thread!"));
724 m_dlgProgress
= new wxProgressDialog
727 "Wait until the thread terminates or press [Cancel]",
733 wxPD_ESTIMATED_TIME
|
737 // thread is not running yet, no need for crit sect
743 void MyFrame::OnWorkerEvent(wxCommandEvent
& event
)
746 WriteText( "Got message from worker thread: " );
747 WriteText( event
.GetString() );
750 int n
= event
.GetInt();
753 m_dlgProgress
->Destroy();
754 m_dlgProgress
= (wxProgressDialog
*)NULL
;
756 // the dialog is aborted because the event came from another thread, so
757 // we may need to wake up the main event loop for the dialog to be
763 if ( !m_dlgProgress
->Update(n
) )
765 wxCriticalSectionLocker
lock(m_critsectWork
);
773 bool MyFrame::Cancelled()
775 wxCriticalSectionLocker
lock(m_critsectWork
);