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();
56 // critical section protects access to all of the fields below
57 wxCriticalSection m_critsect
;
59 // all the threads currently alive - as soon as the thread terminates, it's
60 // removed from the array
61 wxArrayThread m_threads
;
63 // semaphore used to wait for the threads to exit, see MyFrame::OnQuit()
64 wxSemaphore m_semAllDone
;
66 // indicates that we're shutting down and all threads should exit
70 // Create a new application object
73 // Define a new frame type
74 class MyFrame
: public wxFrame
78 MyFrame(wxFrame
*frame
, const wxString
& title
, int x
, int y
, int w
, int h
);
81 // this function is MT-safe, i.e. it can be called from worker threads
82 // safely without any additional locking
83 void LogThreadMessage(const wxString
& text
)
85 wxCriticalSectionLocker
lock(m_csMessages
);
86 m_messages
.push_back(text
);
88 // as we effectively log the messages from the idle event handler,
89 // ensure it's going to be called now that we have some messages to log
93 // accessors for MyWorkerThread (called in its context!)
98 void OnQuit(wxCommandEvent
& event
);
99 void OnClear(wxCommandEvent
& event
);
101 void OnStartThread(wxCommandEvent
& event
);
102 void OnStartThreads(wxCommandEvent
& event
);
103 void OnStopThread(wxCommandEvent
& event
);
104 void OnPauseThread(wxCommandEvent
& event
);
105 void OnResumeThread(wxCommandEvent
& event
);
107 void OnStartWorker(wxCommandEvent
& event
);
108 void OnWorkerEvent(wxCommandEvent
& event
);
109 void OnUpdateWorker(wxUpdateUIEvent
& event
);
111 void OnExecMain(wxCommandEvent
& event
);
112 void OnExecThread(wxCommandEvent
& event
);
114 void OnShowCPUs(wxCommandEvent
& event
);
115 void OnAbout(wxCommandEvent
& event
);
117 void OnIdle(wxIdleEvent
&event
);
119 // helper function - creates a new thread (but doesn't run it)
120 MyThread
*CreateThread();
122 // update display in our status bar: called during idle handling
123 void UpdateThreadStatus();
125 // log the messages queued by LogThreadMessage()
126 void DoLogThreadMessages();
129 // just some place to put our messages in
130 wxTextCtrl
*m_txtctrl
;
132 // the array of pending messages to be displayed and the critical section
134 wxArrayString m_messages
;
135 wxCriticalSection m_csMessages
;
137 // remember the number of running threads and total number of threads
141 // the progress dialog which we show while worker thread is running
142 wxProgressDialog
*m_dlgProgress
;
144 // was the worker thread cancelled by user?
147 // protects m_cancelled
148 wxCriticalSection m_critsectWork
;
150 DECLARE_EVENT_TABLE()
153 // ID for the menu commands
156 THREAD_QUIT
= wxID_EXIT
,
157 THREAD_ABOUT
= wxID_ABOUT
,
160 THREAD_START_THREAD
= 201,
161 THREAD_START_THREADS
,
164 THREAD_RESUME_THREAD
,
172 WORKER_EVENT
// this one gets sent from the worker thread
175 // ----------------------------------------------------------------------------
177 // ----------------------------------------------------------------------------
179 class MyThread
: public wxThread
182 MyThread(MyFrame
*frame
);
185 // thread execution starts here
186 virtual void *Entry();
188 // write something to the text control in the main frame
189 void WriteText(const wxString
& text
)
191 m_frame
->LogThreadMessage(text
);
199 MyThread::MyThread(MyFrame
*frame
)
206 MyThread::~MyThread()
208 wxCriticalSectionLocker
locker(wxGetApp().m_critsect
);
210 wxArrayThread
& threads
= wxGetApp().m_threads
;
211 threads
.Remove(this);
213 if ( threads
.IsEmpty() )
215 // signal the main thread that there are no more threads left if it is
217 if ( wxGetApp().m_shuttingDown
)
219 wxGetApp().m_shuttingDown
= false;
221 wxGetApp().m_semAllDone
.Post();
226 void *MyThread::Entry()
230 text
.Printf(wxT("Thread 0x%lx started (priority = %u).\n"),
231 GetId(), GetPriority());
233 // wxLogMessage(text); -- test wxLog thread safeness
235 for ( m_count
= 0; m_count
< 10; m_count
++ )
237 // check if the application is shutting down: in this case all threads
238 // should stop a.s.a.p.
240 wxCriticalSectionLocker
locker(wxGetApp().m_critsect
);
241 if ( wxGetApp().m_shuttingDown
)
245 // check if just this thread was asked to exit
249 text
.Printf(wxT("[%u] Thread 0x%lx here.\n"), m_count
, GetId());
252 // wxSleep() can't be called from non-GUI thread!
253 wxThread::Sleep(1000);
256 text
.Printf(wxT("Thread 0x%lx finished.\n"), GetId());
258 // wxLogMessage(text); -- test wxLog thread safeness
263 // ----------------------------------------------------------------------------
265 // ----------------------------------------------------------------------------
267 class MyWorkerThread
: public wxThread
270 MyWorkerThread(MyFrame
*frame
);
272 // thread execution starts here
273 virtual void *Entry();
275 // called when the thread exits - whether it terminates normally or is
276 // stopped with Delete() (but not when it is Kill()ed!)
277 virtual void OnExit();
284 MyWorkerThread::MyWorkerThread(MyFrame
*frame
)
291 void MyWorkerThread::OnExit()
295 void *MyWorkerThread::Entry()
297 for ( m_count
= 0; !m_frame
->Cancelled() && (m_count
< 100); m_count
++ )
299 // check if we were asked to exit
303 // create any type of command event here
304 wxCommandEvent
event( wxEVT_COMMAND_MENU_SELECTED
, WORKER_EVENT
);
305 event
.SetInt( m_count
);
307 // send in a thread-safe way
308 wxPostEvent( m_frame
, event
);
313 wxCommandEvent
event( wxEVT_COMMAND_MENU_SELECTED
, WORKER_EVENT
);
314 event
.SetInt(-1); // that's all
315 wxPostEvent( m_frame
, event
);
320 // ----------------------------------------------------------------------------
321 // a thread which simply calls wxExecute
322 // ----------------------------------------------------------------------------
324 class MyExecThread
: public wxThread
327 MyExecThread(const wxChar
*command
) : wxThread(wxTHREAD_JOINABLE
),
333 virtual ExitCode
Entry()
335 return wxUIntToPtr(EXEC(m_command
));
342 // ----------------------------------------------------------------------------
344 // ----------------------------------------------------------------------------
346 BEGIN_EVENT_TABLE(MyFrame
, wxFrame
)
347 EVT_MENU(THREAD_QUIT
, MyFrame::OnQuit
)
348 EVT_MENU(THREAD_CLEAR
, MyFrame::OnClear
)
349 EVT_MENU(THREAD_START_THREAD
, MyFrame::OnStartThread
)
350 EVT_MENU(THREAD_START_THREADS
, MyFrame::OnStartThreads
)
351 EVT_MENU(THREAD_STOP_THREAD
, MyFrame::OnStopThread
)
352 EVT_MENU(THREAD_PAUSE_THREAD
, MyFrame::OnPauseThread
)
353 EVT_MENU(THREAD_RESUME_THREAD
, MyFrame::OnResumeThread
)
355 EVT_MENU(THREAD_EXEC_MAIN
, MyFrame::OnExecMain
)
356 EVT_MENU(THREAD_EXEC_THREAD
, MyFrame::OnExecThread
)
358 EVT_MENU(THREAD_SHOWCPUS
, MyFrame::OnShowCPUs
)
359 EVT_MENU(THREAD_ABOUT
, MyFrame::OnAbout
)
361 EVT_UPDATE_UI(THREAD_START_WORKER
, MyFrame::OnUpdateWorker
)
362 EVT_MENU(THREAD_START_WORKER
, MyFrame::OnStartWorker
)
363 EVT_MENU(WORKER_EVENT
, MyFrame::OnWorkerEvent
)
365 EVT_IDLE(MyFrame::OnIdle
)
370 m_shuttingDown
= 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 wxCriticalSectionLocker
locker(wxGetApp().m_critsect
);
461 // check if we have any threads running first
462 const wxArrayThread
& threads
= wxGetApp().m_threads
;
463 size_t count
= threads
.GetCount();
468 // set the flag indicating that all threads should exit
469 wxGetApp().m_shuttingDown
= true;
472 // now wait for them to really terminate
473 wxGetApp().m_semAllDone
.Wait();
476 MyThread
*MyFrame::CreateThread()
478 MyThread
*thread
= new MyThread(this);
480 if ( thread
->Create() != wxTHREAD_NO_ERROR
)
482 wxLogError(wxT("Can't create thread!"));
485 wxCriticalSectionLocker
enter(wxGetApp().m_critsect
);
486 wxGetApp().m_threads
.Add(thread
);
491 void MyFrame::OnStartThreads(wxCommandEvent
& WXUNUSED(event
) )
495 s_num
= wxGetNumberFromUser(_T("How many threads to start: "), _T(""),
496 _T("wxThread sample"), s_num
, 1, 10000, this);
504 unsigned count
= unsigned(s_num
), n
;
506 wxArrayThread threads
;
508 // first create them all...
509 for ( n
= 0; n
< count
; n
++ )
511 wxThread
*thr
= CreateThread();
513 // we want to show the effect of SetPriority(): the first thread will
514 // have the lowest priority, the second - the highest, all the rest
517 thr
->SetPriority(WXTHREAD_MIN_PRIORITY
);
519 thr
->SetPriority(WXTHREAD_MAX_PRIORITY
);
521 thr
->SetPriority(WXTHREAD_DEFAULT_PRIORITY
);
528 msg
.Printf(wxT("%d new threads created."), count
);
529 SetStatusText(msg
, 1);
530 #endif // wxUSE_STATUSBAR
532 // ...and then start them
533 for ( n
= 0; n
< count
; n
++ )
539 void MyFrame::OnStartThread(wxCommandEvent
& WXUNUSED(event
) )
541 MyThread
*thread
= CreateThread();
543 if ( thread
->Run() != wxTHREAD_NO_ERROR
)
545 wxLogError(wxT("Can't start thread!"));
549 SetStatusText(_T("New thread started."), 1);
550 #endif // wxUSE_STATUSBAR
553 void MyFrame::OnStopThread(wxCommandEvent
& WXUNUSED(event
) )
555 wxCriticalSectionLocker
enter(wxGetApp().m_critsect
);
557 // stop the last thread
558 if ( wxGetApp().m_threads
.IsEmpty() )
560 wxLogError(wxT("No thread to stop!"));
564 wxGetApp().m_threads
.Last()->Delete();
567 SetStatusText(_T("Last thread stopped."), 1);
568 #endif // wxUSE_STATUSBAR
572 void MyFrame::OnResumeThread(wxCommandEvent
& WXUNUSED(event
) )
574 wxCriticalSectionLocker
enter(wxGetApp().m_critsect
);
576 // resume first suspended thread
577 size_t n
= 0, count
= wxGetApp().m_threads
.Count();
578 while ( n
< count
&& !wxGetApp().m_threads
[n
]->IsPaused() )
583 wxLogError(wxT("No thread to resume!"));
587 wxGetApp().m_threads
[n
]->Resume();
590 SetStatusText(_T("Thread resumed."), 1);
591 #endif // wxUSE_STATUSBAR
595 void MyFrame::OnPauseThread(wxCommandEvent
& WXUNUSED(event
) )
597 wxCriticalSectionLocker
enter(wxGetApp().m_critsect
);
599 // pause last running thread
600 int n
= wxGetApp().m_threads
.Count() - 1;
601 while ( n
>= 0 && !wxGetApp().m_threads
[n
]->IsRunning() )
606 wxLogError(wxT("No thread to pause!"));
610 wxGetApp().m_threads
[n
]->Pause();
613 SetStatusText(_T("Thread paused."), 1);
614 #endif // wxUSE_STATUSBAR
618 void MyFrame::OnIdle(wxIdleEvent
& event
)
620 DoLogThreadMessages();
622 UpdateThreadStatus();
627 void MyFrame::DoLogThreadMessages()
629 wxCriticalSectionLocker
lock(m_csMessages
);
631 const size_t count
= m_messages
.size();
632 for ( size_t n
= 0; n
< count
; n
++ )
634 m_txtctrl
->AppendText(m_messages
[n
]);
640 void MyFrame::UpdateThreadStatus()
642 wxCriticalSectionLocker
enter(wxGetApp().m_critsect
);
644 // update the counts of running/total threads
646 nCount
= wxGetApp().m_threads
.Count();
647 for ( size_t n
= 0; n
< nCount
; n
++ )
649 if ( wxGetApp().m_threads
[n
]->IsRunning() )
653 if ( nCount
!= m_nCount
|| nRunning
!= m_nRunning
)
655 m_nRunning
= nRunning
;
658 wxLogStatus(this, wxT("%u threads total, %u running."), unsigned(nCount
), unsigned(nRunning
));
660 //else: avoid flicker - don't print anything
663 void MyFrame::OnQuit(wxCommandEvent
& WXUNUSED(event
) )
668 void MyFrame::OnExecMain(wxCommandEvent
& WXUNUSED(event
))
670 wxLogMessage(wxT("The exit code from the main program is %ld"),
671 EXEC(_T("/bin/echo \"main program\"")));
674 void MyFrame::OnExecThread(wxCommandEvent
& WXUNUSED(event
))
676 MyExecThread
thread(wxT("/bin/echo \"child thread\""));
679 wxLogMessage(wxT("The exit code from a child thread is %ld"),
680 (long)wxPtrToUInt(thread
.Wait()));
683 void MyFrame::OnShowCPUs(wxCommandEvent
& WXUNUSED(event
))
687 int nCPUs
= wxThread::GetCPUCount();
691 msg
= _T("Unknown number of CPUs");
695 msg
= _T("WARNING: you're running without any CPUs!");
699 msg
= _T("This system only has one CPU.");
703 msg
.Printf(wxT("This system has %d CPUs"), nCPUs
);
709 void MyFrame::OnAbout(wxCommandEvent
& WXUNUSED(event
) )
711 wxMessageDialog
dialog(this,
712 _T("wxWidgets multithreaded application sample\n")
713 _T("(c) 1998 Julian Smart, Guilhem Lavaux\n")
714 _T("(c) 1999 Vadim Zeitlin\n")
715 _T("(c) 2000 Robert Roebling"),
716 _T("About wxThread sample"),
717 wxOK
| wxICON_INFORMATION
);
722 void MyFrame::OnClear(wxCommandEvent
& WXUNUSED(event
))
727 void MyFrame::OnUpdateWorker(wxUpdateUIEvent
& event
)
729 event
.Enable( m_dlgProgress
== NULL
);
732 void MyFrame::OnStartWorker(wxCommandEvent
& WXUNUSED(event
))
734 MyWorkerThread
*thread
= new MyWorkerThread(this);
736 if ( thread
->Create() != wxTHREAD_NO_ERROR
)
738 wxLogError(wxT("Can't create thread!"));
742 m_dlgProgress
= new wxProgressDialog
744 _T("Progress dialog"),
745 _T("Wait until the thread terminates or press [Cancel]"),
751 wxPD_ESTIMATED_TIME
|
755 // thread is not running yet, no need for crit sect
761 void MyFrame::OnWorkerEvent(wxCommandEvent
& event
)
763 int n
= event
.GetInt();
766 m_dlgProgress
->Destroy();
767 m_dlgProgress
= (wxProgressDialog
*)NULL
;
769 // the dialog is aborted because the event came from another thread, so
770 // we may need to wake up the main event loop for the dialog to be
776 if ( !m_dlgProgress
->Update(n
) )
778 wxCriticalSectionLocker
lock(m_critsectWork
);
785 bool MyFrame::Cancelled()
787 wxCriticalSectionLocker
lock(m_critsectWork
);