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
);
84 void WriteText(const wxString
& text
) { m_txtctrl
->WriteText(text
); }
86 // accessors for MyWorkerThread (called in its context!)
91 void OnQuit(wxCommandEvent
& event
);
92 void OnClear(wxCommandEvent
& event
);
94 void OnStartThread(wxCommandEvent
& event
);
95 void OnStartThreads(wxCommandEvent
& event
);
96 void OnStopThread(wxCommandEvent
& event
);
97 void OnPauseThread(wxCommandEvent
& event
);
98 void OnResumeThread(wxCommandEvent
& event
);
100 void OnStartWorker(wxCommandEvent
& event
);
101 void OnWorkerEvent(wxCommandEvent
& event
);
102 void OnUpdateWorker(wxUpdateUIEvent
& event
);
104 void OnExecMain(wxCommandEvent
& event
);
105 void OnExecThread(wxCommandEvent
& event
);
107 void OnShowCPUs(wxCommandEvent
& event
);
108 void OnAbout(wxCommandEvent
& event
);
110 void OnIdle(wxIdleEvent
&event
);
113 // helper function - creates a new thread (but doesn't run it)
114 MyThread
*CreateThread();
116 // just some place to put our messages in
117 wxTextCtrl
*m_txtctrl
;
119 // remember the number of running threads and total number of threads
120 size_t m_nRunning
, m_nCount
;
122 // the progress dialog which we show while worker thread is running
123 wxProgressDialog
*m_dlgProgress
;
125 // was the worker thread cancelled by user?
128 // protects m_cancelled
129 wxCriticalSection m_critsectWork
;
131 DECLARE_EVENT_TABLE()
134 // ID for the menu commands
137 THREAD_QUIT
= wxID_EXIT
,
138 THREAD_ABOUT
= wxID_ABOUT
,
141 THREAD_START_THREAD
= 201,
142 THREAD_START_THREADS
,
145 THREAD_RESUME_THREAD
,
153 WORKER_EVENT
// this one gets sent from the worker thread
156 // ----------------------------------------------------------------------------
158 // ----------------------------------------------------------------------------
160 class MyThread
: public wxThread
163 MyThread(MyFrame
*frame
);
165 // thread execution starts here
166 virtual void *Entry();
168 // called when the thread exits - whether it terminates normally or is
169 // stopped with Delete() (but not when it is Kill()ed!)
170 virtual void OnExit();
172 // write something to the text control
173 void WriteText(const wxString
& text
);
180 MyThread::MyThread(MyFrame
*frame
)
187 void MyThread::WriteText(const wxString
& text
)
191 // before doing any GUI calls we must ensure that this thread is the only
197 m_frame
->WriteText(msg
);
202 void MyThread::OnExit()
204 wxCriticalSectionLocker
locker(wxGetApp().m_critsect
);
206 wxArrayThread
& threads
= wxGetApp().m_threads
;
207 threads
.Remove(this);
209 if ( threads
.IsEmpty() )
211 // signal the main thread that there are no more threads left if it is
213 if ( wxGetApp().m_waitingUntilAllDone
)
215 wxGetApp().m_waitingUntilAllDone
= false;
217 wxGetApp().m_semAllDone
.Post();
222 void *MyThread::Entry()
226 text
.Printf(wxT("Thread 0x%lx started (priority = %u).\n"),
227 GetId(), GetPriority());
229 // wxLogMessage(text); -- test wxLog thread safeness
231 for ( m_count
= 0; m_count
< 10; m_count
++ )
233 // check if we were asked to exit
237 text
.Printf(wxT("[%u] Thread 0x%lx here.\n"), m_count
, GetId());
240 // wxSleep() can't be called from non-GUI thread!
241 wxThread::Sleep(1000);
244 text
.Printf(wxT("Thread 0x%lx finished.\n"), GetId());
246 // wxLogMessage(text); -- test wxLog thread safeness
251 // ----------------------------------------------------------------------------
253 // ----------------------------------------------------------------------------
255 class MyWorkerThread
: public wxThread
258 MyWorkerThread(MyFrame
*frame
);
260 // thread execution starts here
261 virtual void *Entry();
263 // called when the thread exits - whether it terminates normally or is
264 // stopped with Delete() (but not when it is Kill()ed!)
265 virtual void OnExit();
272 MyWorkerThread::MyWorkerThread(MyFrame
*frame
)
279 void MyWorkerThread::OnExit()
283 void *MyWorkerThread::Entry()
285 for ( m_count
= 0; !m_frame
->Cancelled() && (m_count
< 100); m_count
++ )
287 // check if we were asked to exit
291 // create any type of command event here
292 wxCommandEvent
event( wxEVT_COMMAND_MENU_SELECTED
, WORKER_EVENT
);
293 event
.SetInt( m_count
);
295 // send in a thread-safe way
296 wxPostEvent( m_frame
, event
);
298 // wxSleep() can't be called from non-main thread!
299 wxThread::Sleep(200);
302 wxCommandEvent
event( wxEVT_COMMAND_MENU_SELECTED
, WORKER_EVENT
);
303 event
.SetInt(-1); // that's all
304 wxPostEvent( m_frame
, event
);
309 // ----------------------------------------------------------------------------
310 // a thread which simply calls wxExecute
311 // ----------------------------------------------------------------------------
313 class MyExecThread
: public wxThread
316 MyExecThread(const wxChar
*command
) : wxThread(wxTHREAD_JOINABLE
),
322 virtual ExitCode
Entry()
324 return (ExitCode
)EXEC(m_command
);
331 // ----------------------------------------------------------------------------
333 // ----------------------------------------------------------------------------
335 BEGIN_EVENT_TABLE(MyFrame
, wxFrame
)
336 EVT_MENU(THREAD_QUIT
, MyFrame::OnQuit
)
337 EVT_MENU(THREAD_CLEAR
, MyFrame::OnClear
)
338 EVT_MENU(THREAD_START_THREAD
, MyFrame::OnStartThread
)
339 EVT_MENU(THREAD_START_THREADS
, MyFrame::OnStartThreads
)
340 EVT_MENU(THREAD_STOP_THREAD
, MyFrame::OnStopThread
)
341 EVT_MENU(THREAD_PAUSE_THREAD
, MyFrame::OnPauseThread
)
342 EVT_MENU(THREAD_RESUME_THREAD
, MyFrame::OnResumeThread
)
344 EVT_MENU(THREAD_EXEC_MAIN
, MyFrame::OnExecMain
)
345 EVT_MENU(THREAD_EXEC_THREAD
, MyFrame::OnExecThread
)
347 EVT_MENU(THREAD_SHOWCPUS
, MyFrame::OnShowCPUs
)
348 EVT_MENU(THREAD_ABOUT
, MyFrame::OnAbout
)
350 EVT_UPDATE_UI(THREAD_START_WORKER
, MyFrame::OnUpdateWorker
)
351 EVT_MENU(THREAD_START_WORKER
, MyFrame::OnStartWorker
)
352 EVT_MENU(WORKER_EVENT
, MyFrame::OnWorkerEvent
)
354 EVT_IDLE(MyFrame::OnIdle
)
360 m_waitingUntilAllDone
= false;
363 // `Main program' equivalent, creating windows and returning main app frame
366 if ( !wxApp::OnInit() )
369 // uncomment this to get some debugging messages from the trace code
370 // on the console (or just set WXTRACE env variable to include "thread")
371 //wxLog::AddTraceMask("thread");
373 // Create the main frame window
374 MyFrame
*frame
= new MyFrame((wxFrame
*)NULL
, _T("wxWidgets threads sample"),
378 wxMenuBar
*menuBar
= new wxMenuBar
;
380 wxMenu
*menuFile
= new wxMenu
;
381 menuFile
->Append(THREAD_CLEAR
, _T("&Clear log\tCtrl-L"));
382 menuFile
->AppendSeparator();
383 menuFile
->Append(THREAD_QUIT
, _T("E&xit\tAlt-X"));
384 menuBar
->Append(menuFile
, _T("&File"));
386 wxMenu
*menuThread
= new wxMenu
;
387 menuThread
->Append(THREAD_START_THREAD
, _T("&Start a new thread\tCtrl-N"));
388 menuThread
->Append(THREAD_START_THREADS
, _T("Start &many threads at once"));
389 menuThread
->Append(THREAD_STOP_THREAD
, _T("S&top a running thread\tCtrl-S"));
390 menuThread
->AppendSeparator();
391 menuThread
->Append(THREAD_PAUSE_THREAD
, _T("&Pause a running thread\tCtrl-P"));
392 menuThread
->Append(THREAD_RESUME_THREAD
, _T("&Resume suspended thread\tCtrl-R"));
393 menuThread
->AppendSeparator();
394 menuThread
->Append(THREAD_START_WORKER
, _T("Start &worker thread\tCtrl-W"));
395 menuBar
->Append(menuThread
, _T("&Thread"));
397 wxMenu
*menuExec
= new wxMenu
;
398 menuExec
->Append(THREAD_EXEC_MAIN
, _T("&Launch a program from main thread\tF5"));
399 menuExec
->Append(THREAD_EXEC_THREAD
, _T("L&aunch a program from a thread\tCtrl-F5"));
400 menuBar
->Append(menuExec
, _T("&Execute"));
402 wxMenu
*menuHelp
= new wxMenu
;
403 menuHelp
->Append(THREAD_SHOWCPUS
, _T("&Show CPU count"));
404 menuHelp
->AppendSeparator();
405 menuHelp
->Append(THREAD_ABOUT
, _T("&About..."));
406 menuBar
->Append(menuHelp
, _T("&Help"));
408 frame
->SetMenuBar(menuBar
);
418 // My frame constructor
419 MyFrame::MyFrame(wxFrame
*frame
, const wxString
& title
,
420 int x
, int y
, int w
, int h
)
421 : wxFrame(frame
, wxID_ANY
, title
, wxPoint(x
, y
), wxSize(w
, h
))
423 SetIcon(wxIcon(sample_xpm
));
425 m_nRunning
= m_nCount
= 0;
427 m_dlgProgress
= (wxProgressDialog
*)NULL
;
431 #endif // wxUSE_STATUSBAR
433 m_txtctrl
= new wxTextCtrl(this, wxID_ANY
, _T(""), wxPoint(0, 0), wxSize(0, 0),
434 wxTE_MULTILINE
| wxTE_READONLY
);
440 // NB: although the OS will terminate all the threads anyhow when the main
441 // one exits, it's good practice to do it ourselves -- even if it's not
442 // completely trivial in this example
444 // tell all the threads to terminate: note that they can't terminate while
445 // we're deleting them because they will block in their OnExit() -- this is
446 // important as otherwise we might access invalid array elements
449 wxGetApp().m_critsect
.Enter();
451 // check if we have any threads running first
452 const wxArrayThread
& threads
= wxGetApp().m_threads
;
453 size_t count
= threads
.GetCount();
457 // set the flag for MyThread::OnExit()
458 wxGetApp().m_waitingUntilAllDone
= true;
461 while ( ! threads
.IsEmpty() )
463 thread
= threads
.Last();
465 wxGetApp().m_critsect
.Leave();
469 wxGetApp().m_critsect
.Enter();
473 wxGetApp().m_critsect
.Leave();
477 // now wait for them to really terminate
478 wxGetApp().m_semAllDone
.Wait();
480 //else: no threads to terminate, no condition to wait for
483 MyThread
*MyFrame::CreateThread()
485 MyThread
*thread
= new MyThread(this);
487 if ( thread
->Create() != wxTHREAD_NO_ERROR
)
489 wxLogError(wxT("Can't create thread!"));
492 wxCriticalSectionLocker
enter(wxGetApp().m_critsect
);
493 wxGetApp().m_threads
.Add(thread
);
498 void MyFrame::OnStartThreads(wxCommandEvent
& WXUNUSED(event
) )
502 s_num
= wxGetNumberFromUser(_T("How many threads to start: "), _T(""),
503 _T("wxThread sample"), s_num
, 1, 10000, this);
511 unsigned count
= unsigned(s_num
), n
;
513 wxArrayThread threads
;
515 // first create them all...
516 for ( n
= 0; n
< count
; n
++ )
518 wxThread
*thr
= CreateThread();
520 // we want to show the effect of SetPriority(): the first thread will
521 // have the lowest priority, the second - the highest, all the rest
524 thr
->SetPriority(WXTHREAD_MIN_PRIORITY
);
526 thr
->SetPriority(WXTHREAD_MAX_PRIORITY
);
528 thr
->SetPriority(WXTHREAD_DEFAULT_PRIORITY
);
535 msg
.Printf(wxT("%d new threads created."), count
);
536 SetStatusText(msg
, 1);
537 #endif // wxUSE_STATUSBAR
539 // ...and then start them
540 for ( n
= 0; n
< count
; n
++ )
546 void MyFrame::OnStartThread(wxCommandEvent
& WXUNUSED(event
) )
548 MyThread
*thread
= CreateThread();
550 if ( thread
->Run() != wxTHREAD_NO_ERROR
)
552 wxLogError(wxT("Can't start thread!"));
556 SetStatusText(_T("New thread started."), 1);
557 #endif // wxUSE_STATUSBAR
560 void MyFrame::OnStopThread(wxCommandEvent
& WXUNUSED(event
) )
562 wxGetApp().m_critsect
.Enter();
564 // stop the last thread
565 if ( wxGetApp().m_threads
.IsEmpty() )
567 wxLogError(wxT("No thread to stop!"));
569 wxGetApp().m_critsect
.Leave();
573 wxThread
*thread
= wxGetApp().m_threads
.Last();
575 // it's important to leave critical section before calling Delete()
576 // because delete will (implicitly) call OnExit() which also tries
577 // to enter the same crit section - would dead lock.
578 wxGetApp().m_critsect
.Leave();
583 SetStatusText(_T("Thread stopped."), 1);
584 #endif // wxUSE_STATUSBAR
588 void MyFrame::OnResumeThread(wxCommandEvent
& WXUNUSED(event
) )
590 wxCriticalSectionLocker
enter(wxGetApp().m_critsect
);
592 // resume first suspended thread
593 size_t n
= 0, count
= wxGetApp().m_threads
.Count();
594 while ( n
< count
&& !wxGetApp().m_threads
[n
]->IsPaused() )
599 wxLogError(wxT("No thread to resume!"));
603 wxGetApp().m_threads
[n
]->Resume();
606 SetStatusText(_T("Thread resumed."), 1);
607 #endif // wxUSE_STATUSBAR
611 void MyFrame::OnPauseThread(wxCommandEvent
& WXUNUSED(event
) )
613 wxCriticalSectionLocker
enter(wxGetApp().m_critsect
);
615 // pause last running thread
616 int n
= wxGetApp().m_threads
.Count() - 1;
617 while ( n
>= 0 && !wxGetApp().m_threads
[n
]->IsRunning() )
622 wxLogError(wxT("No thread to pause!"));
626 wxGetApp().m_threads
[n
]->Pause();
629 SetStatusText(_T("Thread paused."), 1);
630 #endif // wxUSE_STATUSBAR
634 // set the frame title indicating the current number of threads
635 void MyFrame::OnIdle(wxIdleEvent
& event
)
637 wxCriticalSectionLocker
enter(wxGetApp().m_critsect
);
639 // update the counts of running/total threads
641 nCount
= wxGetApp().m_threads
.Count();
642 for ( size_t n
= 0; n
< nCount
; n
++ )
644 if ( wxGetApp().m_threads
[n
]->IsRunning() )
648 if ( nCount
!= m_nCount
|| nRunning
!= m_nRunning
)
650 m_nRunning
= nRunning
;
653 wxLogStatus(this, wxT("%u threads total, %u running."), unsigned(nCount
), unsigned(nRunning
));
655 //else: avoid flicker - don't print anything
660 void MyFrame::OnQuit(wxCommandEvent
& WXUNUSED(event
) )
665 void MyFrame::OnExecMain(wxCommandEvent
& WXUNUSED(event
))
667 wxLogMessage(wxT("The exit code from the main program is %ld"),
668 EXEC(_T("/bin/echo \"main program\"")));
671 void MyFrame::OnExecThread(wxCommandEvent
& WXUNUSED(event
))
673 MyExecThread
thread(wxT("/bin/echo \"child thread\""));
676 wxLogMessage(wxT("The exit code from a child thread is %ld"),
677 (long)thread
.Wait());
680 void MyFrame::OnShowCPUs(wxCommandEvent
& WXUNUSED(event
))
684 int nCPUs
= wxThread::GetCPUCount();
688 msg
= _T("Unknown number of CPUs");
692 msg
= _T("WARNING: you're running without any CPUs!");
696 msg
= _T("This system only has one CPU.");
700 msg
.Printf(wxT("This system has %d CPUs"), nCPUs
);
706 void MyFrame::OnAbout(wxCommandEvent
& WXUNUSED(event
) )
708 wxMessageDialog
dialog(this,
709 _T("wxWidgets multithreaded application sample\n")
710 _T("(c) 1998 Julian Smart, Guilhem Lavaux\n")
711 _T("(c) 1999 Vadim Zeitlin\n")
712 _T("(c) 2000 Robert Roebling"),
713 _T("About wxThread sample"),
714 wxOK
| wxICON_INFORMATION
);
719 void MyFrame::OnClear(wxCommandEvent
& WXUNUSED(event
))
724 void MyFrame::OnUpdateWorker(wxUpdateUIEvent
& event
)
726 event
.Enable( m_dlgProgress
== NULL
);
729 void MyFrame::OnStartWorker(wxCommandEvent
& WXUNUSED(event
))
731 MyWorkerThread
*thread
= new MyWorkerThread(this);
733 if ( thread
->Create() != wxTHREAD_NO_ERROR
)
735 wxLogError(wxT("Can't create thread!"));
739 m_dlgProgress
= new wxProgressDialog
741 _T("Progress dialog"),
742 _T("Wait until the thread terminates or press [Cancel]"),
748 wxPD_ESTIMATED_TIME
|
752 // thread is not running yet, no need for crit sect
758 void MyFrame::OnWorkerEvent(wxCommandEvent
& event
)
761 WriteText( _T("Got message from worker thread: ") );
762 WriteText( event
.GetString() );
763 WriteText( _T("\n") );
765 int n
= event
.GetInt();
768 m_dlgProgress
->Destroy();
769 m_dlgProgress
= (wxProgressDialog
*)NULL
;
771 // the dialog is aborted because the event came from another thread, so
772 // we may need to wake up the main event loop for the dialog to be
778 if ( !m_dlgProgress
->Update(n
) )
780 wxCriticalSectionLocker
lock(m_critsectWork
);
788 bool MyFrame::Cancelled()
790 wxCriticalSectionLocker
lock(m_critsectWork
);