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(wxThreadEvent
& 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
= wxID_HIGHEST
+1 // 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 #define TEST_YIELD_RACE_CONDITION 0
297 void *MyWorkerThread::Entry()
299 #if TEST_YIELD_RACE_CONDITION
303 wxThreadEvent
event( wxEVT_COMMAND_THREAD
, WORKER_EVENT
);
306 wxQueueEvent( m_frame
, new wxThreadEvent(event
) );
309 wxQueueEvent( m_frame
, new wxThreadEvent(event
) );
311 for ( m_count
= 0; !m_frame
->Cancelled() && (m_count
< 100); m_count
++ )
313 // check if we were asked to exit
317 // create any type of command event here
318 wxThreadEvent
event( wxEVT_COMMAND_THREAD
, WORKER_EVENT
);
319 event
.SetInt( m_count
);
321 // send in a thread-safe way
322 wxQueueEvent( m_frame
, new wxThreadEvent(event
) );
327 wxThreadEvent
event( wxEVT_COMMAND_THREAD
, WORKER_EVENT
);
328 event
.SetInt(-1); // that's all
329 wxQueueEvent( m_frame
, new wxThreadEvent(event
) );
335 // ----------------------------------------------------------------------------
336 // a thread which simply calls wxExecute
337 // ----------------------------------------------------------------------------
339 class MyExecThread
: public wxThread
342 MyExecThread(const wxChar
*command
) : wxThread(wxTHREAD_JOINABLE
),
348 virtual ExitCode
Entry()
350 return wxUIntToPtr(EXEC(m_command
));
357 // ----------------------------------------------------------------------------
359 // ----------------------------------------------------------------------------
361 BEGIN_EVENT_TABLE(MyFrame
, wxFrame
)
362 EVT_MENU(THREAD_QUIT
, MyFrame::OnQuit
)
363 EVT_MENU(THREAD_CLEAR
, MyFrame::OnClear
)
364 EVT_MENU(THREAD_START_THREAD
, MyFrame::OnStartThread
)
365 EVT_MENU(THREAD_START_THREADS
, MyFrame::OnStartThreads
)
366 EVT_MENU(THREAD_STOP_THREAD
, MyFrame::OnStopThread
)
367 EVT_MENU(THREAD_PAUSE_THREAD
, MyFrame::OnPauseThread
)
368 EVT_MENU(THREAD_RESUME_THREAD
, MyFrame::OnResumeThread
)
370 EVT_MENU(THREAD_EXEC_MAIN
, MyFrame::OnExecMain
)
371 EVT_MENU(THREAD_EXEC_THREAD
, MyFrame::OnExecThread
)
373 EVT_MENU(THREAD_SHOWCPUS
, MyFrame::OnShowCPUs
)
374 EVT_MENU(THREAD_ABOUT
, MyFrame::OnAbout
)
376 EVT_UPDATE_UI(THREAD_START_WORKER
, MyFrame::OnUpdateWorker
)
377 EVT_MENU(THREAD_START_WORKER
, MyFrame::OnStartWorker
)
379 EVT_THREAD(WORKER_EVENT
, MyFrame::OnWorkerEvent
)
381 EVT_IDLE(MyFrame::OnIdle
)
386 m_shuttingDown
= false;
389 // `Main program' equivalent, creating windows and returning main app frame
392 if ( !wxApp::OnInit() )
395 // uncomment this to get some debugging messages from the trace code
396 // on the console (or just set WXTRACE env variable to include "thread")
397 //wxLog::AddTraceMask("thread");
399 // Create the main frame window
400 MyFrame
*frame
= new MyFrame((wxFrame
*)NULL
, _T("wxWidgets threads sample"),
404 wxMenuBar
*menuBar
= new wxMenuBar
;
406 wxMenu
*menuFile
= new wxMenu
;
407 menuFile
->Append(THREAD_CLEAR
, _T("&Clear log\tCtrl-L"));
408 menuFile
->AppendSeparator();
409 menuFile
->Append(THREAD_QUIT
, _T("E&xit\tAlt-X"));
410 menuBar
->Append(menuFile
, _T("&File"));
412 wxMenu
*menuThread
= new wxMenu
;
413 menuThread
->Append(THREAD_START_THREAD
, _T("&Start a new thread\tCtrl-N"));
414 menuThread
->Append(THREAD_START_THREADS
, _T("Start &many threads at once"));
415 menuThread
->Append(THREAD_STOP_THREAD
, _T("S&top a running thread\tCtrl-S"));
416 menuThread
->AppendSeparator();
417 menuThread
->Append(THREAD_PAUSE_THREAD
, _T("&Pause a running thread\tCtrl-P"));
418 menuThread
->Append(THREAD_RESUME_THREAD
, _T("&Resume suspended thread\tCtrl-R"));
419 menuThread
->AppendSeparator();
420 menuThread
->Append(THREAD_START_WORKER
, _T("Start &worker thread\tCtrl-W"));
421 menuBar
->Append(menuThread
, _T("&Thread"));
423 wxMenu
*menuExec
= new wxMenu
;
424 menuExec
->Append(THREAD_EXEC_MAIN
, _T("&Launch a program from main thread\tF5"));
425 menuExec
->Append(THREAD_EXEC_THREAD
, _T("L&aunch a program from a thread\tCtrl-F5"));
426 menuBar
->Append(menuExec
, _T("&Execute"));
428 wxMenu
*menuHelp
= new wxMenu
;
429 menuHelp
->Append(THREAD_SHOWCPUS
, _T("&Show CPU count"));
430 menuHelp
->AppendSeparator();
431 menuHelp
->Append(THREAD_ABOUT
, _T("&About..."));
432 menuBar
->Append(menuHelp
, _T("&Help"));
434 frame
->SetMenuBar(menuBar
);
444 // My frame constructor
445 MyFrame::MyFrame(wxFrame
*frame
, const wxString
& title
,
446 int x
, int y
, int w
, int h
)
447 : wxFrame(frame
, wxID_ANY
, title
, wxPoint(x
, y
), wxSize(w
, h
))
449 SetIcon(wxIcon(sample_xpm
));
451 m_nRunning
= m_nCount
= 0;
453 m_dlgProgress
= (wxProgressDialog
*)NULL
;
457 #endif // wxUSE_STATUSBAR
459 m_txtctrl
= new wxTextCtrl(this, wxID_ANY
, _T(""), wxPoint(0, 0), wxSize(0, 0),
460 wxTE_MULTILINE
| wxTE_READONLY
);
465 // NB: although the OS will terminate all the threads anyhow when the main
466 // one exits, it's good practice to do it ourselves -- even if it's not
467 // completely trivial in this example
469 // tell all the threads to terminate: note that they can't terminate while
470 // we're deleting them because they will block in their OnExit() -- this is
471 // important as otherwise we might access invalid array elements
474 wxCriticalSectionLocker
locker(wxGetApp().m_critsect
);
476 // check if we have any threads running first
477 const wxArrayThread
& threads
= wxGetApp().m_threads
;
478 size_t count
= threads
.GetCount();
483 // set the flag indicating that all threads should exit
484 wxGetApp().m_shuttingDown
= true;
487 // now wait for them to really terminate
488 wxGetApp().m_semAllDone
.Wait();
491 MyThread
*MyFrame::CreateThread()
493 MyThread
*thread
= new MyThread(this);
495 if ( thread
->Create() != wxTHREAD_NO_ERROR
)
497 wxLogError(wxT("Can't create thread!"));
500 wxCriticalSectionLocker
enter(wxGetApp().m_critsect
);
501 wxGetApp().m_threads
.Add(thread
);
506 void MyFrame::OnStartThreads(wxCommandEvent
& WXUNUSED(event
) )
510 s_num
= wxGetNumberFromUser(_T("How many threads to start: "), _T(""),
511 _T("wxThread sample"), s_num
, 1, 10000, this);
519 unsigned count
= unsigned(s_num
), n
;
521 wxArrayThread threads
;
523 // first create them all...
524 for ( n
= 0; n
< count
; n
++ )
526 wxThread
*thr
= CreateThread();
528 // we want to show the effect of SetPriority(): the first thread will
529 // have the lowest priority, the second - the highest, all the rest
532 thr
->SetPriority(WXTHREAD_MIN_PRIORITY
);
534 thr
->SetPriority(WXTHREAD_MAX_PRIORITY
);
536 thr
->SetPriority(WXTHREAD_DEFAULT_PRIORITY
);
543 msg
.Printf(wxT("%d new threads created."), count
);
544 SetStatusText(msg
, 1);
545 #endif // wxUSE_STATUSBAR
547 // ...and then start them
548 for ( n
= 0; n
< count
; n
++ )
554 void MyFrame::OnStartThread(wxCommandEvent
& WXUNUSED(event
) )
556 MyThread
*thread
= CreateThread();
558 if ( thread
->Run() != wxTHREAD_NO_ERROR
)
560 wxLogError(wxT("Can't start thread!"));
564 SetStatusText(_T("New thread started."), 1);
565 #endif // wxUSE_STATUSBAR
568 void MyFrame::OnStopThread(wxCommandEvent
& WXUNUSED(event
) )
570 wxCriticalSectionLocker
enter(wxGetApp().m_critsect
);
572 // stop the last thread
573 if ( wxGetApp().m_threads
.IsEmpty() )
575 wxLogError(wxT("No thread to stop!"));
579 wxGetApp().m_threads
.Last()->Delete();
582 SetStatusText(_T("Last thread stopped."), 1);
583 #endif // wxUSE_STATUSBAR
587 void MyFrame::OnResumeThread(wxCommandEvent
& WXUNUSED(event
) )
589 wxCriticalSectionLocker
enter(wxGetApp().m_critsect
);
591 // resume first suspended thread
592 size_t n
= 0, count
= wxGetApp().m_threads
.Count();
593 while ( n
< count
&& !wxGetApp().m_threads
[n
]->IsPaused() )
598 wxLogError(wxT("No thread to resume!"));
602 wxGetApp().m_threads
[n
]->Resume();
605 SetStatusText(_T("Thread resumed."), 1);
606 #endif // wxUSE_STATUSBAR
610 void MyFrame::OnPauseThread(wxCommandEvent
& WXUNUSED(event
) )
612 wxCriticalSectionLocker
enter(wxGetApp().m_critsect
);
614 // pause last running thread
615 int n
= wxGetApp().m_threads
.Count() - 1;
616 while ( n
>= 0 && !wxGetApp().m_threads
[n
]->IsRunning() )
621 wxLogError(wxT("No thread to pause!"));
625 wxGetApp().m_threads
[n
]->Pause();
628 SetStatusText(_T("Thread paused."), 1);
629 #endif // wxUSE_STATUSBAR
633 void MyFrame::OnIdle(wxIdleEvent
& event
)
635 DoLogThreadMessages();
637 UpdateThreadStatus();
642 void MyFrame::DoLogThreadMessages()
644 wxCriticalSectionLocker
lock(m_csMessages
);
646 const size_t count
= m_messages
.size();
647 for ( size_t n
= 0; n
< count
; n
++ )
649 m_txtctrl
->AppendText(m_messages
[n
]);
655 void MyFrame::UpdateThreadStatus()
657 wxCriticalSectionLocker
enter(wxGetApp().m_critsect
);
659 // update the counts of running/total threads
661 nCount
= wxGetApp().m_threads
.Count();
662 for ( size_t n
= 0; n
< nCount
; n
++ )
664 if ( wxGetApp().m_threads
[n
]->IsRunning() )
668 if ( nCount
!= m_nCount
|| nRunning
!= m_nRunning
)
670 m_nRunning
= nRunning
;
673 wxLogStatus(this, wxT("%u threads total, %u running."), unsigned(nCount
), unsigned(nRunning
));
675 //else: avoid flicker - don't print anything
678 void MyFrame::OnQuit(wxCommandEvent
& WXUNUSED(event
) )
683 void MyFrame::OnExecMain(wxCommandEvent
& WXUNUSED(event
))
685 wxLogMessage(wxT("The exit code from the main program is %ld"),
686 EXEC(_T("/bin/echo \"main program\"")));
689 void MyFrame::OnExecThread(wxCommandEvent
& WXUNUSED(event
))
691 MyExecThread
thread(wxT("/bin/echo \"child thread\""));
694 wxLogMessage(wxT("The exit code from a child thread is %ld"),
695 (long)wxPtrToUInt(thread
.Wait()));
698 void MyFrame::OnShowCPUs(wxCommandEvent
& WXUNUSED(event
))
702 int nCPUs
= wxThread::GetCPUCount();
706 msg
= _T("Unknown number of CPUs");
710 msg
= _T("WARNING: you're running without any CPUs!");
714 msg
= _T("This system only has one CPU.");
718 msg
.Printf(wxT("This system has %d CPUs"), nCPUs
);
724 void MyFrame::OnAbout(wxCommandEvent
& WXUNUSED(event
) )
726 wxMessageDialog
dialog(this,
727 _T("wxWidgets multithreaded application sample\n")
728 _T("(c) 1998 Julian Smart, Guilhem Lavaux\n")
729 _T("(c) 1999 Vadim Zeitlin\n")
730 _T("(c) 2000 Robert Roebling"),
731 _T("About wxThread sample"),
732 wxOK
| wxICON_INFORMATION
);
737 void MyFrame::OnClear(wxCommandEvent
& WXUNUSED(event
))
742 void MyFrame::OnUpdateWorker(wxUpdateUIEvent
& event
)
744 event
.Enable( m_dlgProgress
== NULL
);
747 void MyFrame::OnStartWorker(wxCommandEvent
& WXUNUSED(event
))
749 MyWorkerThread
*thread
= new MyWorkerThread(this);
751 if ( thread
->Create() != wxTHREAD_NO_ERROR
)
753 wxLogError(wxT("Can't create thread!"));
757 m_dlgProgress
= new wxProgressDialog
759 _T("Progress dialog"),
760 _T("Wait until the thread terminates or press [Cancel]"),
766 wxPD_ESTIMATED_TIME
|
770 // thread is not running yet, no need for crit sect
776 void MyFrame::OnWorkerEvent(wxThreadEvent
& event
)
778 int n
= event
.GetInt();
781 m_dlgProgress
->Destroy();
782 m_dlgProgress
= (wxProgressDialog
*)NULL
;
784 // the dialog is aborted because the event came from another thread, so
785 // we may need to wake up the main event loop for the dialog to be
791 if ( !m_dlgProgress
->Update(n
) )
793 wxCriticalSectionLocker
lock(m_critsectWork
);
800 bool MyFrame::Cancelled()
802 wxCriticalSectionLocker
lock(m_critsectWork
);