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
);
125 void OnShowCPUs(wxCommandEvent
& event
);
126 void OnAbout(wxCommandEvent
& event
);
128 void OnIdle(wxIdleEvent
&event
);
129 void OnWorkerEvent(wxThreadEvent
& event
);
130 void OnUpdateWorker(wxUpdateUIEvent
& event
);
133 // thread helper functions
134 // -----------------------
136 // helper function - creates a new thread (but doesn't run it)
137 MyThread
*CreateThread();
139 // update display in our status bar: called during idle handling
140 void UpdateThreadStatus();
142 // log the messages queued by LogThreadMessage()
143 void DoLogThreadMessages();
146 // internal variables
147 // ------------------
149 // just some place to put our messages in
150 wxTextCtrl
*m_txtctrl
;
152 // the array of pending messages to be displayed and the critical section
154 wxArrayString m_messages
;
155 wxCriticalSection m_csMessages
;
157 // remember the number of running threads and total number of threads
161 // the progress dialog which we show while worker thread is running
162 wxProgressDialog
*m_dlgProgress
;
164 // was the worker thread cancelled by user?
167 // protects m_cancelled
168 wxCriticalSection m_critsectWork
;
170 DECLARE_EVENT_TABLE()
173 // ----------------------------------------------------------------------------
175 // ----------------------------------------------------------------------------
177 // ID for the menu commands
180 THREAD_QUIT
= wxID_EXIT
,
181 THREAD_ABOUT
= wxID_ABOUT
,
184 THREAD_START_THREAD
= 201,
185 THREAD_START_THREADS
,
188 THREAD_RESUME_THREAD
,
196 WORKER_EVENT
= wxID_HIGHEST
+1 // this one gets sent from the worker thread
199 // ----------------------------------------------------------------------------
201 // ----------------------------------------------------------------------------
203 class MyThread
: public wxThread
206 MyThread(MyFrame
*frame
);
209 // thread execution starts here
210 virtual void *Entry();
212 // write something to the text control in the main frame
213 void WriteText(const wxString
& text
)
215 m_frame
->LogThreadMessage(text
);
223 // ----------------------------------------------------------------------------
225 // ----------------------------------------------------------------------------
227 class MyWorkerThread
: public wxThread
230 MyWorkerThread(MyFrame
*frame
);
232 // thread execution starts here
233 virtual void *Entry();
235 // called when the thread exits - whether it terminates normally or is
236 // stopped with Delete() (but not when it is Kill()ed!)
237 virtual void OnExit();
244 // ============================================================================
246 // ============================================================================
248 // ----------------------------------------------------------------------------
249 // the application class
250 // ----------------------------------------------------------------------------
252 // Create a new application object
257 m_shuttingDown
= false;
260 // `Main program' equivalent, creating windows and returning main app frame
263 if ( !wxApp::OnInit() )
266 // uncomment this to get some debugging messages from the trace code
267 // on the console (or just set WXTRACE env variable to include "thread")
268 wxLog::AddTraceMask("thread");
270 // Create the main frame window
271 MyFrame
*frame
= new MyFrame((wxFrame
*)NULL
, _T("wxWidgets threads sample"),
281 // ----------------------------------------------------------------------------
283 // ----------------------------------------------------------------------------
285 BEGIN_EVENT_TABLE(MyFrame
, wxFrame
)
286 EVT_MENU(THREAD_QUIT
, MyFrame::OnQuit
)
287 EVT_MENU(THREAD_CLEAR
, MyFrame::OnClear
)
288 EVT_MENU(THREAD_START_THREAD
, MyFrame::OnStartThread
)
289 EVT_MENU(THREAD_START_THREADS
, MyFrame::OnStartThreads
)
290 EVT_MENU(THREAD_STOP_THREAD
, MyFrame::OnStopThread
)
291 EVT_MENU(THREAD_PAUSE_THREAD
, MyFrame::OnPauseThread
)
292 EVT_MENU(THREAD_RESUME_THREAD
, MyFrame::OnResumeThread
)
293 EVT_MENU(THREAD_START_WORKER
, MyFrame::OnStartWorker
)
294 EVT_MENU(THREAD_EXEC_MAIN
, MyFrame::OnExecMain
)
296 EVT_MENU(THREAD_SHOWCPUS
, MyFrame::OnShowCPUs
)
297 EVT_MENU(THREAD_ABOUT
, MyFrame::OnAbout
)
299 EVT_UPDATE_UI(THREAD_START_WORKER
, MyFrame::OnUpdateWorker
)
300 EVT_THREAD(WORKER_EVENT
, MyFrame::OnWorkerEvent
)
301 EVT_IDLE(MyFrame::OnIdle
)
304 // My frame constructor
305 MyFrame::MyFrame(wxFrame
*frame
, const wxString
& title
,
306 int x
, int y
, int w
, int h
)
307 : wxFrame(frame
, wxID_ANY
, title
, wxPoint(x
, y
), wxSize(w
, h
))
309 SetIcon(wxIcon(sample_xpm
));
312 wxMenuBar
*menuBar
= new wxMenuBar
;
314 wxMenu
*menuFile
= new wxMenu
;
315 menuFile
->Append(THREAD_CLEAR
, _T("&Clear log\tCtrl-L"));
316 menuFile
->AppendSeparator();
317 menuFile
->Append(THREAD_QUIT
, _T("E&xit\tAlt-X"));
318 menuBar
->Append(menuFile
, _T("&File"));
320 wxMenu
*menuThread
= new wxMenu
;
321 menuThread
->Append(THREAD_START_THREAD
, _T("&Start a new thread\tCtrl-N"));
322 menuThread
->Append(THREAD_START_THREADS
, _T("Start &many threads at once"));
323 menuThread
->Append(THREAD_STOP_THREAD
, _T("S&top the last spawned thread\tCtrl-S"));
324 menuThread
->AppendSeparator();
325 menuThread
->Append(THREAD_PAUSE_THREAD
, _T("&Pause the last spawned running thread\tCtrl-P"));
326 menuThread
->Append(THREAD_RESUME_THREAD
, _T("&Resume the first suspended thread\tCtrl-R"));
327 menuThread
->AppendSeparator();
328 menuThread
->Append(THREAD_START_WORKER
, _T("Start a &worker thread\tCtrl-W"));
329 menuThread
->Append(THREAD_EXEC_MAIN
, _T("&Launch a program from main thread\tF5"));
330 menuBar
->Append(menuThread
, _T("&Thread"));
332 wxMenu
*menuHelp
= new wxMenu
;
333 menuHelp
->Append(THREAD_SHOWCPUS
, _T("&Show CPU count"));
334 menuHelp
->AppendSeparator();
335 menuHelp
->Append(THREAD_ABOUT
, _T("&About..."));
336 menuBar
->Append(menuHelp
, _T("&Help"));
340 m_nRunning
= m_nCount
= 0;
342 m_dlgProgress
= (wxProgressDialog
*)NULL
;
346 #endif // wxUSE_STATUSBAR
348 m_txtctrl
= new wxTextCtrl(this, wxID_ANY
, _T(""), wxPoint(0, 0), wxSize(0, 0),
349 wxTE_MULTILINE
| wxTE_READONLY
);
354 // NB: although the OS will terminate all the threads anyhow when the main
355 // one exits, it's good practice to do it ourselves -- even if it's not
356 // completely trivial in this example
358 // tell all the threads to terminate: note that they can't terminate while
359 // we're deleting them because they will block in their OnExit() -- this is
360 // important as otherwise we might access invalid array elements
363 wxCriticalSectionLocker
locker(wxGetApp().m_critsect
);
365 // check if we have any threads running first
366 const wxArrayThread
& threads
= wxGetApp().m_threads
;
367 size_t count
= threads
.GetCount();
372 // set the flag indicating that all threads should exit
373 wxGetApp().m_shuttingDown
= true;
376 // now wait for them to really terminate
377 wxGetApp().m_semAllDone
.Wait();
380 MyThread
*MyFrame::CreateThread()
382 MyThread
*thread
= new MyThread(this);
384 if ( thread
->Create() != wxTHREAD_NO_ERROR
)
386 wxLogError(wxT("Can't create thread!"));
389 wxCriticalSectionLocker
enter(wxGetApp().m_critsect
);
390 wxGetApp().m_threads
.Add(thread
);
395 void MyFrame::OnStartThreads(wxCommandEvent
& WXUNUSED(event
) )
399 s_num
= wxGetNumberFromUser(_T("How many threads to start: "), _T(""),
400 _T("wxThread sample"), s_num
, 1, 10000, this);
408 unsigned count
= unsigned(s_num
), n
;
410 wxArrayThread threads
;
412 // first create them all...
413 for ( n
= 0; n
< count
; n
++ )
415 wxThread
*thr
= CreateThread();
417 // we want to show the effect of SetPriority(): the first thread will
418 // have the lowest priority, the second - the highest, all the rest
421 thr
->SetPriority(WXTHREAD_MIN_PRIORITY
);
423 thr
->SetPriority(WXTHREAD_MAX_PRIORITY
);
425 thr
->SetPriority(WXTHREAD_DEFAULT_PRIORITY
);
432 msg
.Printf(wxT("%d new threads created."), count
);
433 SetStatusText(msg
, 1);
434 #endif // wxUSE_STATUSBAR
436 // ...and then start them
437 for ( n
= 0; n
< count
; n
++ )
443 void MyFrame::OnStartThread(wxCommandEvent
& WXUNUSED(event
) )
445 MyThread
*thread
= CreateThread();
447 if ( thread
->Run() != wxTHREAD_NO_ERROR
)
449 wxLogError(wxT("Can't start thread!"));
453 SetStatusText(_T("New thread started."), 1);
454 #endif // wxUSE_STATUSBAR
457 void MyFrame::OnStopThread(wxCommandEvent
& WXUNUSED(event
) )
459 wxCriticalSectionLocker
enter(wxGetApp().m_critsect
);
461 // stop the last thread
462 if ( wxGetApp().m_threads
.IsEmpty() )
464 wxLogError(wxT("No thread to stop!"));
468 wxGetApp().m_threads
.Last()->Delete();
471 SetStatusText(_T("Last thread stopped."), 1);
472 #endif // wxUSE_STATUSBAR
476 void MyFrame::OnResumeThread(wxCommandEvent
& WXUNUSED(event
) )
478 wxCriticalSectionLocker
enter(wxGetApp().m_critsect
);
480 // resume first suspended thread
481 size_t n
= 0, count
= wxGetApp().m_threads
.Count();
482 while ( n
< count
&& !wxGetApp().m_threads
[n
]->IsPaused() )
487 wxLogError(wxT("No thread to resume!"));
491 wxGetApp().m_threads
[n
]->Resume();
494 SetStatusText(_T("Thread resumed."), 1);
495 #endif // wxUSE_STATUSBAR
499 void MyFrame::OnPauseThread(wxCommandEvent
& WXUNUSED(event
) )
501 wxCriticalSectionLocker
enter(wxGetApp().m_critsect
);
503 // pause last running thread
504 int n
= wxGetApp().m_threads
.Count() - 1;
505 while ( n
>= 0 && !wxGetApp().m_threads
[n
]->IsRunning() )
510 wxLogError(wxT("No thread to pause!"));
514 wxGetApp().m_threads
[n
]->Pause();
517 SetStatusText(_T("Thread paused."), 1);
518 #endif // wxUSE_STATUSBAR
522 void MyFrame::OnIdle(wxIdleEvent
& event
)
524 DoLogThreadMessages();
526 UpdateThreadStatus();
531 void MyFrame::DoLogThreadMessages()
533 wxCriticalSectionLocker
lock(m_csMessages
);
535 const size_t count
= m_messages
.size();
536 for ( size_t n
= 0; n
< count
; n
++ )
538 m_txtctrl
->AppendText(m_messages
[n
]);
544 void MyFrame::UpdateThreadStatus()
546 wxCriticalSectionLocker
enter(wxGetApp().m_critsect
);
548 // update the counts of running/total threads
550 nCount
= wxGetApp().m_threads
.Count();
551 for ( size_t n
= 0; n
< nCount
; n
++ )
553 if ( wxGetApp().m_threads
[n
]->IsRunning() )
557 if ( nCount
!= m_nCount
|| nRunning
!= m_nRunning
)
559 m_nRunning
= nRunning
;
562 wxLogStatus(this, wxT("%u threads total, %u running."), unsigned(nCount
), unsigned(nRunning
));
564 //else: avoid flicker - don't print anything
567 void MyFrame::OnQuit(wxCommandEvent
& WXUNUSED(event
) )
572 void MyFrame::OnExecMain(wxCommandEvent
& WXUNUSED(event
))
574 wxString cmd
= wxGetTextFromUser("Please enter the command to execute",
579 "/bin/echo \"Message from another process\"",
583 return; // user clicked cancel
585 wxLogMessage(wxT("The exit code from the main program is %ld"),
589 void MyFrame::OnShowCPUs(wxCommandEvent
& WXUNUSED(event
))
593 int nCPUs
= wxThread::GetCPUCount();
597 msg
= _T("Unknown number of CPUs");
601 msg
= _T("WARNING: you're running without any CPUs!");
605 msg
= _T("This system only has one CPU.");
609 msg
.Printf(wxT("This system has %d CPUs"), nCPUs
);
615 void MyFrame::OnAbout(wxCommandEvent
& WXUNUSED(event
) )
617 wxMessageDialog
dialog(this,
618 _T("wxWidgets multithreaded application sample\n")
619 _T("(c) 1998 Julian Smart, Guilhem Lavaux\n")
620 _T("(c) 1999 Vadim Zeitlin\n")
621 _T("(c) 2000 Robert Roebling"),
622 _T("About wxThread sample"),
623 wxOK
| wxICON_INFORMATION
);
628 void MyFrame::OnClear(wxCommandEvent
& WXUNUSED(event
))
633 void MyFrame::OnUpdateWorker(wxUpdateUIEvent
& event
)
635 event
.Enable( m_dlgProgress
== NULL
);
638 void MyFrame::OnStartWorker(wxCommandEvent
& WXUNUSED(event
))
640 MyWorkerThread
*thread
= new MyWorkerThread(this);
642 if ( thread
->Create() != wxTHREAD_NO_ERROR
)
644 wxLogError(wxT("Can't create thread!"));
648 m_dlgProgress
= new wxProgressDialog
650 _T("Progress dialog"),
651 _T("Wait until the thread terminates or press [Cancel]"),
657 wxPD_ESTIMATED_TIME
|
661 // thread is not running yet, no need for crit sect
667 void MyFrame::OnWorkerEvent(wxThreadEvent
& event
)
669 int n
= event
.GetInt();
672 m_dlgProgress
->Destroy();
673 m_dlgProgress
= (wxProgressDialog
*)NULL
;
675 // the dialog is aborted because the event came from another thread, so
676 // we may need to wake up the main event loop for the dialog to be
682 if ( !m_dlgProgress
->Update(n
) )
684 wxCriticalSectionLocker
lock(m_critsectWork
);
691 bool MyFrame::Cancelled()
693 wxCriticalSectionLocker
lock(m_critsectWork
);
699 // ----------------------------------------------------------------------------
701 // ----------------------------------------------------------------------------
703 MyThread::MyThread(MyFrame
*frame
)
710 MyThread::~MyThread()
712 wxCriticalSectionLocker
locker(wxGetApp().m_critsect
);
714 wxArrayThread
& threads
= wxGetApp().m_threads
;
715 threads
.Remove(this);
717 if ( threads
.IsEmpty() )
719 // signal the main thread that there are no more threads left if it is
721 if ( wxGetApp().m_shuttingDown
)
723 wxGetApp().m_shuttingDown
= false;
725 wxGetApp().m_semAllDone
.Post();
730 void *MyThread::Entry()
734 text
.Printf(wxT("Thread %p started (priority = %u).\n"),
735 GetId(), GetPriority());
737 // wxLogMessage(text); -- test wxLog thread safeness
739 for ( m_count
= 0; m_count
< 10; m_count
++ )
741 // check if the application is shutting down: in this case all threads
742 // should stop a.s.a.p.
744 wxCriticalSectionLocker
locker(wxGetApp().m_critsect
);
745 if ( wxGetApp().m_shuttingDown
)
749 // check if just this thread was asked to exit
753 text
.Printf(wxT("[%u] Thread %p here.\n"), m_count
, GetId());
756 // wxSleep() can't be called from non-GUI thread!
757 wxThread::Sleep(1000);
760 text
.Printf(wxT("Thread %p finished.\n"), GetId());
762 // wxLogMessage(text); -- test wxLog thread safeness
768 // ----------------------------------------------------------------------------
770 // ----------------------------------------------------------------------------
772 MyWorkerThread::MyWorkerThread(MyFrame
*frame
)
779 void MyWorkerThread::OnExit()
783 // define this symbol to 1 to test if the YieldFor() call in the wxProgressDialog::Update
784 // function provokes a race condition in which the second wxThreadEvent posted by
785 // MyWorkerThread::Entry is processed by the YieldFor() call of wxProgressDialog::Update
786 // and results in the destruction of the progress dialog itself, resulting in a crash later.
787 #define TEST_YIELD_RACE_CONDITION 0
789 void *MyWorkerThread::Entry()
791 #if TEST_YIELD_RACE_CONDITION
795 wxThreadEvent
event( wxEVT_COMMAND_THREAD
, WORKER_EVENT
);
798 wxQueueEvent( m_frame
, event
.Clone() );
801 wxQueueEvent( m_frame
, event
.Clone() );
803 for ( m_count
= 0; !m_frame
->Cancelled() && (m_count
< 100); m_count
++ )
805 // check if we were asked to exit
809 // create any type of command event here
810 wxThreadEvent
event( wxEVT_COMMAND_THREAD
, WORKER_EVENT
);
811 event
.SetInt( m_count
);
813 // send in a thread-safe way
814 wxQueueEvent( m_frame
, event
.Clone() );
819 wxThreadEvent
event( wxEVT_COMMAND_THREAD
, WORKER_EVENT
);
820 event
.SetInt(-1); // that's all
821 wxQueueEvent( m_frame
, event
.Clone() );