1 /////////////////////////////////////////////////////////////////////////////
3 // Purpose: wxWidgets thread sample
4 // Author: Guilhem Lavaux, Vadim Zeitlin
8 // Copyright: (c) 1998-2002 wxWidgets 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"
29 #include "wx/numdlg.h"
31 #include "wx/progdlg.h"
33 #include "../sample.xpm"
35 // define this to use wxExecute in the exec tests, otherwise just use system
39 #define EXEC(cmd) wxExecute((cmd), wxEXEC_SYNC)
41 #define EXEC(cmd) system(cmd)
45 WX_DEFINE_ARRAY_PTR(wxThread
*, wxArrayThread
);
47 // Define a new application type
48 class MyApp
: public wxApp
54 virtual bool OnInit();
57 // all the threads currently alive - as soon as the thread terminates, it's
58 // removed from the array
59 wxArrayThread m_threads
;
61 // crit section protects access to all of the arrays below
62 wxCriticalSection m_critsect
;
64 // semaphore used to wait for the threads to exit, see MyFrame::OnQuit()
65 wxSemaphore m_semAllDone
;
67 // the last exiting thread should post to m_semAllDone 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 // this function is MT-safe, i.e. it can be called from worker threads
84 // safely without any additional locking
85 void LogThreadMessage(const wxString
& text
)
87 wxCriticalSectionLocker
lock(m_csMessages
);
88 m_messages
.push_back(text
);
90 // as we effectively log the messages from the idle event handler,
91 // ensure it's going to be called now that we have some messages to log
95 // accessors for MyWorkerThread (called in its context!)
100 void OnQuit(wxCommandEvent
& event
);
101 void OnClear(wxCommandEvent
& event
);
103 void OnStartThread(wxCommandEvent
& event
);
104 void OnStartThreads(wxCommandEvent
& event
);
105 void OnStopThread(wxCommandEvent
& event
);
106 void OnPauseThread(wxCommandEvent
& event
);
107 void OnResumeThread(wxCommandEvent
& event
);
109 void OnStartWorker(wxCommandEvent
& event
);
110 void OnWorkerEvent(wxCommandEvent
& event
);
111 void OnUpdateWorker(wxUpdateUIEvent
& event
);
113 void OnExecMain(wxCommandEvent
& event
);
114 void OnExecThread(wxCommandEvent
& event
);
116 void OnShowCPUs(wxCommandEvent
& event
);
117 void OnAbout(wxCommandEvent
& event
);
119 void OnIdle(wxIdleEvent
&event
);
121 // helper function - creates a new thread (but doesn't run it)
122 MyThread
*CreateThread();
124 // update display in our status bar: called during idle handling
125 void UpdateThreadStatus();
127 // log the messages queued by LogThreadMessage()
128 void DoLogThreadMessages();
131 // just some place to put our messages in
132 wxTextCtrl
*m_txtctrl
;
134 // the array of pending messages to be displayed and the critical section
136 wxArrayString m_messages
;
137 wxCriticalSection m_csMessages
;
139 // remember the number of running threads and total number of threads
143 // the progress dialog which we show while worker thread is running
144 wxProgressDialog
*m_dlgProgress
;
146 // was the worker thread cancelled by user?
149 // protects m_cancelled
150 wxCriticalSection m_critsectWork
;
152 DECLARE_EVENT_TABLE()
155 // ID for the menu commands
158 THREAD_QUIT
= wxID_EXIT
,
159 THREAD_ABOUT
= wxID_ABOUT
,
162 THREAD_START_THREAD
= 201,
163 THREAD_START_THREADS
,
166 THREAD_RESUME_THREAD
,
174 WORKER_EVENT
// this one gets sent from the worker thread
177 // ----------------------------------------------------------------------------
179 // ----------------------------------------------------------------------------
181 class MyThread
: public wxThread
184 MyThread(MyFrame
*frame
);
186 // thread execution starts here
187 virtual void *Entry();
189 // called when the thread exits - whether it terminates normally or is
190 // stopped with Delete() (but not when it is Kill()ed!)
191 virtual void OnExit();
193 // write something to the text control
194 void WriteText(const wxString
& text
);
201 MyThread::MyThread(MyFrame
*frame
)
208 void MyThread::WriteText(const wxString
& text
)
210 m_frame
->LogThreadMessage(text
);
213 void MyThread::OnExit()
215 wxCriticalSectionLocker
locker(wxGetApp().m_critsect
);
217 wxArrayThread
& threads
= wxGetApp().m_threads
;
218 threads
.Remove(this);
220 if ( threads
.IsEmpty() )
222 // signal the main thread that there are no more threads left if it is
224 if ( wxGetApp().m_waitingUntilAllDone
)
226 wxGetApp().m_waitingUntilAllDone
= false;
228 wxGetApp().m_semAllDone
.Post();
233 void *MyThread::Entry()
237 text
.Printf(wxT("Thread 0x%lx started (priority = %u).\n"),
238 GetId(), GetPriority());
240 // wxLogMessage(text); -- test wxLog thread safeness
242 for ( m_count
= 0; m_count
< 10; m_count
++ )
244 // check if we were asked to exit
248 text
.Printf(wxT("[%u] Thread 0x%lx here.\n"), m_count
, GetId());
251 // wxSleep() can't be called from non-GUI thread!
252 wxThread::Sleep(1000);
255 text
.Printf(wxT("Thread 0x%lx finished.\n"), GetId());
257 // wxLogMessage(text); -- test wxLog thread safeness
262 // ----------------------------------------------------------------------------
264 // ----------------------------------------------------------------------------
266 class MyWorkerThread
: public wxThread
269 MyWorkerThread(MyFrame
*frame
);
271 // thread execution starts here
272 virtual void *Entry();
274 // called when the thread exits - whether it terminates normally or is
275 // stopped with Delete() (but not when it is Kill()ed!)
276 virtual void OnExit();
283 MyWorkerThread::MyWorkerThread(MyFrame
*frame
)
290 void MyWorkerThread::OnExit()
294 void *MyWorkerThread::Entry()
296 for ( m_count
= 0; !m_frame
->Cancelled() && (m_count
< 100); m_count
++ )
298 // check if we were asked to exit
302 // create any type of command event here
303 wxCommandEvent
event( wxEVT_COMMAND_MENU_SELECTED
, WORKER_EVENT
);
304 event
.SetInt( m_count
);
306 // send in a thread-safe way
307 wxPostEvent( m_frame
, event
);
312 wxCommandEvent
event( wxEVT_COMMAND_MENU_SELECTED
, WORKER_EVENT
);
313 event
.SetInt(-1); // that's all
314 wxPostEvent( m_frame
, event
);
319 // ----------------------------------------------------------------------------
320 // a thread which simply calls wxExecute
321 // ----------------------------------------------------------------------------
323 class MyExecThread
: public wxThread
326 MyExecThread(const wxChar
*command
) : wxThread(wxTHREAD_JOINABLE
),
332 virtual ExitCode
Entry()
334 return wxUIntToPtr(EXEC(m_command
));
341 // ----------------------------------------------------------------------------
343 // ----------------------------------------------------------------------------
345 BEGIN_EVENT_TABLE(MyFrame
, wxFrame
)
346 EVT_MENU(THREAD_QUIT
, MyFrame::OnQuit
)
347 EVT_MENU(THREAD_CLEAR
, MyFrame::OnClear
)
348 EVT_MENU(THREAD_START_THREAD
, MyFrame::OnStartThread
)
349 EVT_MENU(THREAD_START_THREADS
, MyFrame::OnStartThreads
)
350 EVT_MENU(THREAD_STOP_THREAD
, MyFrame::OnStopThread
)
351 EVT_MENU(THREAD_PAUSE_THREAD
, MyFrame::OnPauseThread
)
352 EVT_MENU(THREAD_RESUME_THREAD
, MyFrame::OnResumeThread
)
354 EVT_MENU(THREAD_EXEC_MAIN
, MyFrame::OnExecMain
)
355 EVT_MENU(THREAD_EXEC_THREAD
, MyFrame::OnExecThread
)
357 EVT_MENU(THREAD_SHOWCPUS
, MyFrame::OnShowCPUs
)
358 EVT_MENU(THREAD_ABOUT
, MyFrame::OnAbout
)
360 EVT_UPDATE_UI(THREAD_START_WORKER
, MyFrame::OnUpdateWorker
)
361 EVT_MENU(THREAD_START_WORKER
, MyFrame::OnStartWorker
)
362 EVT_MENU(WORKER_EVENT
, MyFrame::OnWorkerEvent
)
364 EVT_IDLE(MyFrame::OnIdle
)
370 m_waitingUntilAllDone
= false;
373 // `Main program' equivalent, creating windows and returning main app frame
376 if ( !wxApp::OnInit() )
379 // uncomment this to get some debugging messages from the trace code
380 // on the console (or just set WXTRACE env variable to include "thread")
381 //wxLog::AddTraceMask("thread");
383 // Create the main frame window
384 MyFrame
*frame
= new MyFrame((wxFrame
*)NULL
, _T("wxWidgets threads sample"),
388 wxMenuBar
*menuBar
= new wxMenuBar
;
390 wxMenu
*menuFile
= new wxMenu
;
391 menuFile
->Append(THREAD_CLEAR
, _T("&Clear log\tCtrl-L"));
392 menuFile
->AppendSeparator();
393 menuFile
->Append(THREAD_QUIT
, _T("E&xit\tAlt-X"));
394 menuBar
->Append(menuFile
, _T("&File"));
396 wxMenu
*menuThread
= new wxMenu
;
397 menuThread
->Append(THREAD_START_THREAD
, _T("&Start a new thread\tCtrl-N"));
398 menuThread
->Append(THREAD_START_THREADS
, _T("Start &many threads at once"));
399 menuThread
->Append(THREAD_STOP_THREAD
, _T("S&top a running thread\tCtrl-S"));
400 menuThread
->AppendSeparator();
401 menuThread
->Append(THREAD_PAUSE_THREAD
, _T("&Pause a running thread\tCtrl-P"));
402 menuThread
->Append(THREAD_RESUME_THREAD
, _T("&Resume suspended thread\tCtrl-R"));
403 menuThread
->AppendSeparator();
404 menuThread
->Append(THREAD_START_WORKER
, _T("Start &worker thread\tCtrl-W"));
405 menuBar
->Append(menuThread
, _T("&Thread"));
407 wxMenu
*menuExec
= new wxMenu
;
408 menuExec
->Append(THREAD_EXEC_MAIN
, _T("&Launch a program from main thread\tF5"));
409 menuExec
->Append(THREAD_EXEC_THREAD
, _T("L&aunch a program from a thread\tCtrl-F5"));
410 menuBar
->Append(menuExec
, _T("&Execute"));
412 wxMenu
*menuHelp
= new wxMenu
;
413 menuHelp
->Append(THREAD_SHOWCPUS
, _T("&Show CPU count"));
414 menuHelp
->AppendSeparator();
415 menuHelp
->Append(THREAD_ABOUT
, _T("&About..."));
416 menuBar
->Append(menuHelp
, _T("&Help"));
418 frame
->SetMenuBar(menuBar
);
428 // My frame constructor
429 MyFrame::MyFrame(wxFrame
*frame
, const wxString
& title
,
430 int x
, int y
, int w
, int h
)
431 : wxFrame(frame
, wxID_ANY
, title
, wxPoint(x
, y
), wxSize(w
, h
))
433 SetIcon(wxIcon(sample_xpm
));
435 m_nRunning
= m_nCount
= 0;
437 m_dlgProgress
= (wxProgressDialog
*)NULL
;
441 #endif // wxUSE_STATUSBAR
443 m_txtctrl
= new wxTextCtrl(this, wxID_ANY
, _T(""), wxPoint(0, 0), wxSize(0, 0),
444 wxTE_MULTILINE
| wxTE_READONLY
);
450 // NB: although the OS will terminate all the threads anyhow when the main
451 // one exits, it's good practice to do it ourselves -- even if it's not
452 // completely trivial in this example
454 // tell all the threads to terminate: note that they can't terminate while
455 // we're deleting them because they will block in their OnExit() -- this is
456 // important as otherwise we might access invalid array elements
459 wxGetApp().m_critsect
.Enter();
461 // check if we have any threads running first
462 const wxArrayThread
& threads
= wxGetApp().m_threads
;
463 size_t count
= threads
.GetCount();
467 // set the flag for MyThread::OnExit()
468 wxGetApp().m_waitingUntilAllDone
= true;
471 while ( ! threads
.IsEmpty() )
473 thread
= threads
.Last();
475 wxGetApp().m_critsect
.Leave();
479 wxGetApp().m_critsect
.Enter();
483 wxGetApp().m_critsect
.Leave();
487 // now wait for them to really terminate
488 wxGetApp().m_semAllDone
.Wait();
490 //else: no threads to terminate, no condition to wait for
493 MyThread
*MyFrame::CreateThread()
495 MyThread
*thread
= new MyThread(this);
497 if ( thread
->Create() != wxTHREAD_NO_ERROR
)
499 wxLogError(wxT("Can't create thread!"));
502 wxCriticalSectionLocker
enter(wxGetApp().m_critsect
);
503 wxGetApp().m_threads
.Add(thread
);
508 void MyFrame::OnStartThreads(wxCommandEvent
& WXUNUSED(event
) )
512 s_num
= wxGetNumberFromUser(_T("How many threads to start: "), _T(""),
513 _T("wxThread sample"), s_num
, 1, 10000, this);
521 unsigned count
= unsigned(s_num
), n
;
523 wxArrayThread threads
;
525 // first create them all...
526 for ( n
= 0; n
< count
; n
++ )
528 wxThread
*thr
= CreateThread();
530 // we want to show the effect of SetPriority(): the first thread will
531 // have the lowest priority, the second - the highest, all the rest
534 thr
->SetPriority(WXTHREAD_MIN_PRIORITY
);
536 thr
->SetPriority(WXTHREAD_MAX_PRIORITY
);
538 thr
->SetPriority(WXTHREAD_DEFAULT_PRIORITY
);
545 msg
.Printf(wxT("%d new threads created."), count
);
546 SetStatusText(msg
, 1);
547 #endif // wxUSE_STATUSBAR
549 // ...and then start them
550 for ( n
= 0; n
< count
; n
++ )
556 void MyFrame::OnStartThread(wxCommandEvent
& WXUNUSED(event
) )
558 MyThread
*thread
= CreateThread();
560 if ( thread
->Run() != wxTHREAD_NO_ERROR
)
562 wxLogError(wxT("Can't start thread!"));
566 SetStatusText(_T("New thread started."), 1);
567 #endif // wxUSE_STATUSBAR
570 void MyFrame::OnStopThread(wxCommandEvent
& WXUNUSED(event
) )
572 wxGetApp().m_critsect
.Enter();
574 // stop the last thread
575 if ( wxGetApp().m_threads
.IsEmpty() )
577 wxLogError(wxT("No thread to stop!"));
579 wxGetApp().m_critsect
.Leave();
583 wxThread
*thread
= wxGetApp().m_threads
.Last();
585 // it's important to leave critical section before calling Delete()
586 // because delete will (implicitly) call OnExit() which also tries
587 // to enter the same crit section - would dead lock.
588 wxGetApp().m_critsect
.Leave();
593 SetStatusText(_T("Thread stopped."), 1);
594 #endif // wxUSE_STATUSBAR
598 void MyFrame::OnResumeThread(wxCommandEvent
& WXUNUSED(event
) )
600 wxCriticalSectionLocker
enter(wxGetApp().m_critsect
);
602 // resume first suspended thread
603 size_t n
= 0, count
= wxGetApp().m_threads
.Count();
604 while ( n
< count
&& !wxGetApp().m_threads
[n
]->IsPaused() )
609 wxLogError(wxT("No thread to resume!"));
613 wxGetApp().m_threads
[n
]->Resume();
616 SetStatusText(_T("Thread resumed."), 1);
617 #endif // wxUSE_STATUSBAR
621 void MyFrame::OnPauseThread(wxCommandEvent
& WXUNUSED(event
) )
623 wxCriticalSectionLocker
enter(wxGetApp().m_critsect
);
625 // pause last running thread
626 int n
= wxGetApp().m_threads
.Count() - 1;
627 while ( n
>= 0 && !wxGetApp().m_threads
[n
]->IsRunning() )
632 wxLogError(wxT("No thread to pause!"));
636 wxGetApp().m_threads
[n
]->Pause();
639 SetStatusText(_T("Thread paused."), 1);
640 #endif // wxUSE_STATUSBAR
644 void MyFrame::OnIdle(wxIdleEvent
& event
)
646 DoLogThreadMessages();
648 UpdateThreadStatus();
653 void MyFrame::DoLogThreadMessages()
655 wxCriticalSectionLocker
lock(m_csMessages
);
657 const size_t count
= m_messages
.size();
658 for ( size_t n
= 0; n
< count
; n
++ )
660 m_txtctrl
->AppendText(m_messages
[n
]);
666 void MyFrame::UpdateThreadStatus()
668 wxCriticalSectionLocker
enter(wxGetApp().m_critsect
);
670 // update the counts of running/total threads
672 nCount
= wxGetApp().m_threads
.Count();
673 for ( size_t n
= 0; n
< nCount
; n
++ )
675 if ( wxGetApp().m_threads
[n
]->IsRunning() )
679 if ( nCount
!= m_nCount
|| nRunning
!= m_nRunning
)
681 m_nRunning
= nRunning
;
684 wxLogStatus(this, wxT("%u threads total, %u running."), unsigned(nCount
), unsigned(nRunning
));
686 //else: avoid flicker - don't print anything
689 void MyFrame::OnQuit(wxCommandEvent
& WXUNUSED(event
) )
694 void MyFrame::OnExecMain(wxCommandEvent
& WXUNUSED(event
))
696 wxLogMessage(wxT("The exit code from the main program is %ld"),
697 EXEC(_T("/bin/echo \"main program\"")));
700 void MyFrame::OnExecThread(wxCommandEvent
& WXUNUSED(event
))
702 MyExecThread
thread(wxT("/bin/echo \"child thread\""));
705 wxLogMessage(wxT("The exit code from a child thread is %ld"),
706 (long)wxPtrToUInt(thread
.Wait()));
709 void MyFrame::OnShowCPUs(wxCommandEvent
& WXUNUSED(event
))
713 int nCPUs
= wxThread::GetCPUCount();
717 msg
= _T("Unknown number of CPUs");
721 msg
= _T("WARNING: you're running without any CPUs!");
725 msg
= _T("This system only has one CPU.");
729 msg
.Printf(wxT("This system has %d CPUs"), nCPUs
);
735 void MyFrame::OnAbout(wxCommandEvent
& WXUNUSED(event
) )
737 wxMessageDialog
dialog(this,
738 _T("wxWidgets multithreaded application sample\n")
739 _T("(c) 1998 Julian Smart, Guilhem Lavaux\n")
740 _T("(c) 1999 Vadim Zeitlin\n")
741 _T("(c) 2000 Robert Roebling"),
742 _T("About wxThread sample"),
743 wxOK
| wxICON_INFORMATION
);
748 void MyFrame::OnClear(wxCommandEvent
& WXUNUSED(event
))
753 void MyFrame::OnUpdateWorker(wxUpdateUIEvent
& event
)
755 event
.Enable( m_dlgProgress
== NULL
);
758 void MyFrame::OnStartWorker(wxCommandEvent
& WXUNUSED(event
))
760 MyWorkerThread
*thread
= new MyWorkerThread(this);
762 if ( thread
->Create() != wxTHREAD_NO_ERROR
)
764 wxLogError(wxT("Can't create thread!"));
768 m_dlgProgress
= new wxProgressDialog
770 _T("Progress dialog"),
771 _T("Wait until the thread terminates or press [Cancel]"),
777 wxPD_ESTIMATED_TIME
|
781 // thread is not running yet, no need for crit sect
787 void MyFrame::OnWorkerEvent(wxCommandEvent
& event
)
789 int n
= event
.GetInt();
792 m_dlgProgress
->Destroy();
793 m_dlgProgress
= (wxProgressDialog
*)NULL
;
795 // the dialog is aborted because the event came from another thread, so
796 // we may need to wake up the main event loop for the dialog to be
802 if ( !m_dlgProgress
->Update(n
) )
804 wxCriticalSectionLocker
lock(m_critsectWork
);
811 bool MyFrame::Cancelled()
813 wxCriticalSectionLocker
lock(m_critsectWork
);