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 // ============================================================================
14 // ============================================================================
16 // ----------------------------------------------------------------------------
18 // ----------------------------------------------------------------------------
20 // For compilers that support precompilation, includes "wx/wx.h".
21 #include "wx/wxprec.h"
32 #error "This sample requires thread support!"
33 #endif // wxUSE_THREADS
35 #include "wx/thread.h"
36 #include "wx/dynarray.h"
37 #include "wx/numdlg.h"
38 #include "wx/progdlg.h"
40 // ----------------------------------------------------------------------------
42 // ----------------------------------------------------------------------------
44 #include "../sample.xpm"
46 // ----------------------------------------------------------------------------
48 // ----------------------------------------------------------------------------
50 // define this to use wxExecute in the exec tests, otherwise just use system
54 #define EXEC(cmd) wxExecute((cmd), wxEXEC_SYNC)
56 #define EXEC(cmd) system(cmd)
60 WX_DEFINE_ARRAY_PTR(wxThread
*, wxArrayThread
);
62 // Define a new application type
63 class MyApp
: public wxApp
69 virtual bool OnInit();
71 // critical section protects access to all of the fields below
72 wxCriticalSection m_critsect
;
74 // all the threads currently alive - as soon as the thread terminates, it's
75 // removed from the array
76 wxArrayThread m_threads
;
78 // semaphore used to wait for the threads to exit, see MyFrame::OnQuit()
79 wxSemaphore m_semAllDone
;
81 // indicates that we're shutting down and all threads should exit
85 // Define a new frame type
86 class MyFrame
: public wxFrame
90 MyFrame(wxFrame
*frame
, const wxString
& title
, int x
, int y
, int w
, int h
);
93 // this function is MT-safe, i.e. it can be called from worker threads
94 // safely without any additional locking
95 void LogThreadMessage(const wxString
& text
)
97 wxCriticalSectionLocker
lock(m_csMessages
);
98 m_messages
.push_back(text
);
100 // as we effectively log the messages from the idle event handler,
101 // ensure it's going to be called now that we have some messages to log
105 // accessors for MyWorkerThread (called in its context!)
112 void OnQuit(wxCommandEvent
& event
);
113 void OnClear(wxCommandEvent
& event
);
115 void OnStartThread(wxCommandEvent
& event
);
116 void OnStartThreads(wxCommandEvent
& event
);
117 void OnStopThread(wxCommandEvent
& event
);
118 void OnPauseThread(wxCommandEvent
& event
);
119 void OnResumeThread(wxCommandEvent
& event
);
121 void OnStartWorker(wxCommandEvent
& event
);
123 void OnExecMain(wxCommandEvent
& event
);
124 void OnExecThread(wxCommandEvent
& event
);
126 void OnShowCPUs(wxCommandEvent
& event
);
127 void OnAbout(wxCommandEvent
& event
);
129 void OnIdle(wxIdleEvent
&event
);
130 void OnWorkerEvent(wxThreadEvent
& event
);
131 void OnUpdateWorker(wxUpdateUIEvent
& event
);
134 // thread helper functions
135 // -----------------------
137 // helper function - creates a new thread (but doesn't run it)
138 MyThread
*CreateThread();
140 // update display in our status bar: called during idle handling
141 void UpdateThreadStatus();
143 // log the messages queued by LogThreadMessage()
144 void DoLogThreadMessages();
147 // internal variables
148 // ------------------
150 // just some place to put our messages in
151 wxTextCtrl
*m_txtctrl
;
153 // the array of pending messages to be displayed and the critical section
155 wxArrayString m_messages
;
156 wxCriticalSection m_csMessages
;
158 // remember the number of running threads and total number of threads
162 // the progress dialog which we show while worker thread is running
163 wxProgressDialog
*m_dlgProgress
;
165 // was the worker thread cancelled by user?
168 // protects m_cancelled
169 wxCriticalSection m_critsectWork
;
171 DECLARE_EVENT_TABLE()
174 // ----------------------------------------------------------------------------
176 // ----------------------------------------------------------------------------
178 // ID for the menu commands
181 THREAD_QUIT
= wxID_EXIT
,
182 THREAD_ABOUT
= wxID_ABOUT
,
185 THREAD_START_THREAD
= 201,
186 THREAD_START_THREADS
,
189 THREAD_RESUME_THREAD
,
197 WORKER_EVENT
= wxID_HIGHEST
+1 // this one gets sent from the worker thread
200 // ----------------------------------------------------------------------------
202 // ----------------------------------------------------------------------------
204 class MyThread
: public wxThread
207 MyThread(MyFrame
*frame
);
210 // thread execution starts here
211 virtual void *Entry();
213 // write something to the text control in the main frame
214 void WriteText(const wxString
& text
)
216 m_frame
->LogThreadMessage(text
);
224 // ----------------------------------------------------------------------------
226 // ----------------------------------------------------------------------------
228 class MyWorkerThread
: public wxThread
231 MyWorkerThread(MyFrame
*frame
);
233 // thread execution starts here
234 virtual void *Entry();
236 // called when the thread exits - whether it terminates normally or is
237 // stopped with Delete() (but not when it is Kill()ed!)
238 virtual void OnExit();
245 // ----------------------------------------------------------------------------
246 // a thread which simply calls wxExecute
247 // ----------------------------------------------------------------------------
249 class MyExecThread
: public wxThread
252 MyExecThread(const wxChar
*command
) : wxThread(wxTHREAD_JOINABLE
),
258 virtual ExitCode
Entry()
260 return wxUIntToPtr(EXEC(m_command
));
267 // ============================================================================
269 // ============================================================================
271 // ----------------------------------------------------------------------------
272 // the application class
273 // ----------------------------------------------------------------------------
275 // Create a new application object
280 m_shuttingDown
= false;
283 // `Main program' equivalent, creating windows and returning main app frame
286 if ( !wxApp
::OnInit() )
289 // uncomment this to get some debugging messages from the trace code
290 // on the console (or just set WXTRACE env variable to include "thread")
291 wxLog
::AddTraceMask("thread");
293 // Create the main frame window
294 MyFrame
*frame
= new MyFrame((wxFrame
*)NULL
, _T("wxWidgets threads sample"),
304 // ----------------------------------------------------------------------------
306 // ----------------------------------------------------------------------------
308 BEGIN_EVENT_TABLE(MyFrame
, wxFrame
)
309 EVT_MENU(THREAD_QUIT
, MyFrame
::OnQuit
)
310 EVT_MENU(THREAD_CLEAR
, MyFrame
::OnClear
)
311 EVT_MENU(THREAD_START_THREAD
, MyFrame
::OnStartThread
)
312 EVT_MENU(THREAD_START_THREADS
, MyFrame
::OnStartThreads
)
313 EVT_MENU(THREAD_STOP_THREAD
, MyFrame
::OnStopThread
)
314 EVT_MENU(THREAD_PAUSE_THREAD
, MyFrame
::OnPauseThread
)
315 EVT_MENU(THREAD_RESUME_THREAD
, MyFrame
::OnResumeThread
)
317 EVT_MENU(THREAD_EXEC_MAIN
, MyFrame
::OnExecMain
)
318 EVT_MENU(THREAD_EXEC_THREAD
, MyFrame
::OnExecThread
)
320 EVT_MENU(THREAD_SHOWCPUS
, MyFrame
::OnShowCPUs
)
321 EVT_MENU(THREAD_ABOUT
, MyFrame
::OnAbout
)
323 EVT_MENU(THREAD_START_WORKER
, MyFrame
::OnStartWorker
)
325 EVT_UPDATE_UI(THREAD_START_WORKER
, MyFrame
::OnUpdateWorker
)
326 EVT_THREAD(WORKER_EVENT
, MyFrame
::OnWorkerEvent
)
327 EVT_IDLE(MyFrame
::OnIdle
)
330 // My frame constructor
331 MyFrame
::MyFrame(wxFrame
*frame
, const wxString
& title
,
332 int x
, int y
, int w
, int h
)
333 : wxFrame(frame
, wxID_ANY
, title
, wxPoint(x
, y
), wxSize(w
, h
))
335 SetIcon(wxIcon(sample_xpm
));
338 wxMenuBar
*menuBar
= new wxMenuBar
;
340 wxMenu
*menuFile
= new wxMenu
;
341 menuFile
->Append(THREAD_CLEAR
, _T("&Clear log\tCtrl-L"));
342 menuFile
->AppendSeparator();
343 menuFile
->Append(THREAD_QUIT
, _T("E&xit\tAlt-X"));
344 menuBar
->Append(menuFile
, _T("&File"));
346 wxMenu
*menuThread
= new wxMenu
;
347 menuThread
->Append(THREAD_START_THREAD
, _T("&Start a new thread\tCtrl-N"));
348 menuThread
->Append(THREAD_START_THREADS
, _T("Start &many threads at once"));
349 menuThread
->Append(THREAD_STOP_THREAD
, _T("S&top the last spawned thread\tCtrl-S"));
350 menuThread
->AppendSeparator();
351 menuThread
->Append(THREAD_PAUSE_THREAD
, _T("&Pause the last spawned running thread\tCtrl-P"));
352 menuThread
->Append(THREAD_RESUME_THREAD
, _T("&Resume the first suspended thread\tCtrl-R"));
353 menuThread
->AppendSeparator();
354 menuThread
->Append(THREAD_START_WORKER
, _T("Start a &worker thread\tCtrl-W"));
355 menuBar
->Append(menuThread
, _T("&Thread"));
357 wxMenu
*menuExec
= new wxMenu
;
358 menuExec
->Append(THREAD_EXEC_MAIN
, _T("&Launch a program from main thread\tF5"));
359 menuExec
->Append(THREAD_EXEC_THREAD
, _T("L&aunch a program from a thread\tCtrl-F5"));
360 menuBar
->Append(menuExec
, _T("&Execute"));
362 wxMenu
*menuHelp
= new wxMenu
;
363 menuHelp
->Append(THREAD_SHOWCPUS
, _T("&Show CPU count"));
364 menuHelp
->AppendSeparator();
365 menuHelp
->Append(THREAD_ABOUT
, _T("&About..."));
366 menuBar
->Append(menuHelp
, _T("&Help"));
370 m_nRunning
= m_nCount
= 0;
372 m_dlgProgress
= (wxProgressDialog
*)NULL
;
376 #endif // wxUSE_STATUSBAR
378 m_txtctrl
= new wxTextCtrl(this, wxID_ANY
, _T(""), wxPoint(0, 0), wxSize(0, 0),
379 wxTE_MULTILINE
| wxTE_READONLY
);
384 // NB: although the OS will terminate all the threads anyhow when the main
385 // one exits, it's good practice to do it ourselves -- even if it's not
386 // completely trivial in this example
388 // tell all the threads to terminate: note that they can't terminate while
389 // we're deleting them because they will block in their OnExit() -- this is
390 // important as otherwise we might access invalid array elements
393 wxCriticalSectionLocker
locker(wxGetApp().m_critsect
);
395 // check if we have any threads running first
396 const wxArrayThread
& threads
= wxGetApp().m_threads
;
397 size_t count
= threads
.GetCount();
402 // set the flag indicating that all threads should exit
403 wxGetApp().m_shuttingDown
= true;
406 // now wait for them to really terminate
407 wxGetApp().m_semAllDone
.Wait();
410 MyThread
*MyFrame
::CreateThread()
412 MyThread
*thread
= new MyThread(this);
414 if ( thread
->Create() != wxTHREAD_NO_ERROR
)
416 wxLogError(wxT("Can't create thread!"));
419 wxCriticalSectionLocker
enter(wxGetApp().m_critsect
);
420 wxGetApp().m_threads
.Add(thread
);
425 void MyFrame
::OnStartThreads(wxCommandEvent
& WXUNUSED(event
) )
429 s_num
= wxGetNumberFromUser(_T("How many threads to start: "), _T(""),
430 _T("wxThread sample"), s_num
, 1, 10000, this);
438 unsigned count
= unsigned(s_num
), n
;
440 wxArrayThread threads
;
442 // first create them all...
443 for ( n
= 0; n
< count
; n
++ )
445 wxThread
*thr
= CreateThread();
447 // we want to show the effect of SetPriority(): the first thread will
448 // have the lowest priority, the second - the highest, all the rest
451 thr
->SetPriority(WXTHREAD_MIN_PRIORITY
);
453 thr
->SetPriority(WXTHREAD_MAX_PRIORITY
);
455 thr
->SetPriority(WXTHREAD_DEFAULT_PRIORITY
);
462 msg
.Printf(wxT("%d new threads created."), count
);
463 SetStatusText(msg
, 1);
464 #endif // wxUSE_STATUSBAR
466 // ...and then start them
467 for ( n
= 0; n
< count
; n
++ )
473 void MyFrame
::OnStartThread(wxCommandEvent
& WXUNUSED(event
) )
475 MyThread
*thread
= CreateThread();
477 if ( thread
->Run() != wxTHREAD_NO_ERROR
)
479 wxLogError(wxT("Can't start thread!"));
483 SetStatusText(_T("New thread started."), 1);
484 #endif // wxUSE_STATUSBAR
487 void MyFrame
::OnStopThread(wxCommandEvent
& WXUNUSED(event
) )
489 wxCriticalSectionLocker
enter(wxGetApp().m_critsect
);
491 // stop the last thread
492 if ( wxGetApp().m_threads
.IsEmpty() )
494 wxLogError(wxT("No thread to stop!"));
498 wxGetApp().m_threads
.Last()->Delete();
501 SetStatusText(_T("Last thread stopped."), 1);
502 #endif // wxUSE_STATUSBAR
506 void MyFrame
::OnResumeThread(wxCommandEvent
& WXUNUSED(event
) )
508 wxCriticalSectionLocker
enter(wxGetApp().m_critsect
);
510 // resume first suspended thread
511 size_t n
= 0, count
= wxGetApp().m_threads
.Count();
512 while ( n
< count
&& !wxGetApp().m_threads
[n
]->IsPaused() )
517 wxLogError(wxT("No thread to resume!"));
521 wxGetApp().m_threads
[n
]->Resume();
524 SetStatusText(_T("Thread resumed."), 1);
525 #endif // wxUSE_STATUSBAR
529 void MyFrame
::OnPauseThread(wxCommandEvent
& WXUNUSED(event
) )
531 wxCriticalSectionLocker
enter(wxGetApp().m_critsect
);
533 // pause last running thread
534 int n
= wxGetApp().m_threads
.Count() - 1;
535 while ( n
>= 0 && !wxGetApp().m_threads
[n
]->IsRunning() )
540 wxLogError(wxT("No thread to pause!"));
544 wxGetApp().m_threads
[n
]->Pause();
547 SetStatusText(_T("Thread paused."), 1);
548 #endif // wxUSE_STATUSBAR
552 void MyFrame
::OnIdle(wxIdleEvent
& event
)
554 DoLogThreadMessages();
556 UpdateThreadStatus();
561 void MyFrame
::DoLogThreadMessages()
563 wxCriticalSectionLocker
lock(m_csMessages
);
565 const size_t count
= m_messages
.size();
566 for ( size_t n
= 0; n
< count
; n
++ )
568 m_txtctrl
->AppendText(m_messages
[n
]);
574 void MyFrame
::UpdateThreadStatus()
576 wxCriticalSectionLocker
enter(wxGetApp().m_critsect
);
578 // update the counts of running/total threads
580 nCount
= wxGetApp().m_threads
.Count();
581 for ( size_t n
= 0; n
< nCount
; n
++ )
583 if ( wxGetApp().m_threads
[n
]->IsRunning() )
587 if ( nCount
!= m_nCount
|| nRunning
!= m_nRunning
)
589 m_nRunning
= nRunning
;
592 wxLogStatus(this, wxT("%u threads total, %u running."), unsigned(nCount
), unsigned(nRunning
));
594 //else: avoid flicker - don't print anything
597 void MyFrame
::OnQuit(wxCommandEvent
& WXUNUSED(event
) )
602 void MyFrame
::OnExecMain(wxCommandEvent
& WXUNUSED(event
))
604 wxLogMessage(wxT("The exit code from the main program is %ld"),
605 EXEC(_T("/bin/echo \"main program\"")));
608 void MyFrame
::OnExecThread(wxCommandEvent
& WXUNUSED(event
))
610 MyExecThread
thread(wxT("/bin/echo \"child thread\""));
613 wxLogMessage(wxT("The exit code from a child thread is %ld"),
614 (long)wxPtrToUInt(thread
.Wait()));
617 void MyFrame
::OnShowCPUs(wxCommandEvent
& WXUNUSED(event
))
621 int nCPUs
= wxThread
::GetCPUCount();
625 msg
= _T("Unknown number of CPUs");
629 msg
= _T("WARNING: you're running without any CPUs!");
633 msg
= _T("This system only has one CPU.");
637 msg
.Printf(wxT("This system has %d CPUs"), nCPUs
);
643 void MyFrame
::OnAbout(wxCommandEvent
& WXUNUSED(event
) )
645 wxMessageDialog
dialog(this,
646 _T("wxWidgets multithreaded application sample\n")
647 _T("(c) 1998 Julian Smart, Guilhem Lavaux\n")
648 _T("(c) 1999 Vadim Zeitlin\n")
649 _T("(c) 2000 Robert Roebling"),
650 _T("About wxThread sample"),
651 wxOK
| wxICON_INFORMATION
);
656 void MyFrame
::OnClear(wxCommandEvent
& WXUNUSED(event
))
661 void MyFrame
::OnUpdateWorker(wxUpdateUIEvent
& event
)
663 event
.Enable( m_dlgProgress
== NULL
);
666 void MyFrame
::OnStartWorker(wxCommandEvent
& WXUNUSED(event
))
668 MyWorkerThread
*thread
= new MyWorkerThread(this);
670 if ( thread
->Create() != wxTHREAD_NO_ERROR
)
672 wxLogError(wxT("Can't create thread!"));
676 m_dlgProgress
= new wxProgressDialog
678 _T("Progress dialog"),
679 _T("Wait until the thread terminates or press [Cancel]"),
685 wxPD_ESTIMATED_TIME
|
689 // thread is not running yet, no need for crit sect
695 void MyFrame
::OnWorkerEvent(wxThreadEvent
& event
)
697 int n
= event
.GetInt();
700 m_dlgProgress
->Destroy();
701 m_dlgProgress
= (wxProgressDialog
*)NULL
;
703 // the dialog is aborted because the event came from another thread, so
704 // we may need to wake up the main event loop for the dialog to be
710 if ( !m_dlgProgress
->Update(n
) )
712 wxCriticalSectionLocker
lock(m_critsectWork
);
719 bool MyFrame
::Cancelled()
721 wxCriticalSectionLocker
lock(m_critsectWork
);
727 // ----------------------------------------------------------------------------
729 // ----------------------------------------------------------------------------
731 MyThread
::MyThread(MyFrame
*frame
)
738 MyThread
::~MyThread()
740 wxCriticalSectionLocker
locker(wxGetApp().m_critsect
);
742 wxArrayThread
& threads
= wxGetApp().m_threads
;
743 threads
.Remove(this);
745 if ( threads
.IsEmpty() )
747 // signal the main thread that there are no more threads left if it is
749 if ( wxGetApp().m_shuttingDown
)
751 wxGetApp().m_shuttingDown
= false;
753 wxGetApp().m_semAllDone
.Post();
758 void *MyThread
::Entry()
762 text
.Printf(wxT("Thread %p started (priority = %u).\n"),
763 GetId(), GetPriority());
765 // wxLogMessage(text); -- test wxLog thread safeness
767 for ( m_count
= 0; m_count
< 10; m_count
++ )
769 // check if the application is shutting down: in this case all threads
770 // should stop a.s.a.p.
772 wxCriticalSectionLocker
locker(wxGetApp().m_critsect
);
773 if ( wxGetApp().m_shuttingDown
)
777 // check if just this thread was asked to exit
781 text
.Printf(wxT("[%u] Thread %p here.\n"), m_count
, GetId());
784 // wxSleep() can't be called from non-GUI thread!
785 wxThread
::Sleep(1000);
788 text
.Printf(wxT("Thread %p finished.\n"), GetId());
790 // wxLogMessage(text); -- test wxLog thread safeness
796 // ----------------------------------------------------------------------------
798 // ----------------------------------------------------------------------------
800 MyWorkerThread
::MyWorkerThread(MyFrame
*frame
)
807 void MyWorkerThread
::OnExit()
811 // define this symbol to 1 to test if the YieldFor() call in the wxProgressDialog::Update
812 // function provokes a race condition in which the second wxThreadEvent posted by
813 // MyWorkerThread::Entry is processed by the YieldFor() call of wxProgressDialog::Update
814 // and results in the destruction of the progress dialog itself, resulting in a crash later.
815 #define TEST_YIELD_RACE_CONDITION 0
817 void *MyWorkerThread
::Entry()
819 #if TEST_YIELD_RACE_CONDITION
823 wxThreadEvent
event( wxEVT_COMMAND_THREAD
, WORKER_EVENT
);
826 wxQueueEvent( m_frame
, event
.Clone() );
829 wxQueueEvent( m_frame
, event
.Clone() );
831 for ( m_count
= 0; !m_frame
->Cancelled() && (m_count
< 100); m_count
++ )
833 // check if we were asked to exit
837 // create any type of command event here
838 wxThreadEvent
event( wxEVT_COMMAND_THREAD
, WORKER_EVENT
);
839 event
.SetInt( m_count
);
841 // send in a thread-safe way
842 wxQueueEvent( m_frame
, event
.Clone() );
847 wxThreadEvent
event( wxEVT_COMMAND_THREAD
, WORKER_EVENT
);
848 event
.SetInt(-1); // that's all
849 wxQueueEvent( m_frame
, event
.Clone() );