1 /////////////////////////////////////////////////////////////////////////////
3 // Purpose: wxWindows thread sample
4 // Author: Guilhem Lavaux, Vadim Zeitlin
8 // Copyright: (c) 1998-2002 wxWindows 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"
30 #include "wx/progdlg.h"
32 // define this to use wxExecute in the exec tests, otherwise just use system
36 #define EXEC(cmd) wxExecute((cmd), wxEXEC_SYNC)
38 #define EXEC(cmd) system(cmd)
42 WX_DEFINE_ARRAY(wxThread
*, wxArrayThread
);
44 // Define a new application type
45 class MyApp
: public wxApp
51 virtual bool OnInit();
54 // all the threads currently alive - as soon as the thread terminates, it's
55 // removed from the array
56 wxArrayThread m_threads
;
58 // crit section protects access to all of the arrays below
59 wxCriticalSection m_critsect
;
61 // the (mutex, condition) pair used to wait for the threads to exit, see
63 wxMutex m_mutexAllDone
;
64 wxCondition m_condAllDone
;
66 // the last exiting thread should signal m_condAllDone if this is true
67 // (protected by the same m_critsect)
68 bool m_waitingUntilAllDone
;
71 // Create a new application object
74 // Define a new frame type
75 class MyFrame
: public wxFrame
79 MyFrame(wxFrame
*frame
, const wxString
& title
, int x
, int y
, int w
, int h
);
82 void WriteText(const wxString
& text
) { m_txtctrl
->WriteText(text
); }
84 // accessors for MyWorkerThread (called in its context!)
89 void OnQuit(wxCommandEvent
& event
);
90 void OnClear(wxCommandEvent
& event
);
92 void OnStartThread(wxCommandEvent
& event
);
93 void OnStartThreads(wxCommandEvent
& event
);
94 void OnStopThread(wxCommandEvent
& event
);
95 void OnPauseThread(wxCommandEvent
& event
);
96 void OnResumeThread(wxCommandEvent
& event
);
98 void OnStartWorker(wxCommandEvent
& event
);
99 void OnWorkerEvent(wxCommandEvent
& event
);
100 void OnUpdateWorker(wxUpdateUIEvent
& event
);
102 void OnExecMain(wxCommandEvent
& event
);
103 void OnExecThread(wxCommandEvent
& event
);
105 void OnShowCPUs(wxCommandEvent
& event
);
106 void OnAbout(wxCommandEvent
& event
);
108 void OnIdle(wxIdleEvent
&event
);
111 // helper function - creates a new thread (but doesn't run it)
112 MyThread
*CreateThread();
114 // just some place to put our messages in
115 wxTextCtrl
*m_txtctrl
;
117 // remember the number of running threads and total number of threads
118 size_t m_nRunning
, m_nCount
;
120 // the progress dialog which we show while worker thread is running
121 wxProgressDialog
*m_dlgProgress
;
123 // was the worker thread cancelled by user?
126 // protects m_cancelled
127 wxCriticalSection m_critsectWork
;
129 DECLARE_EVENT_TABLE()
132 // ID for the menu commands
138 THREAD_START_THREAD
= 201,
139 THREAD_START_THREADS
,
142 THREAD_RESUME_THREAD
,
151 WORKER_EVENT
// this one gets sent from the worker thread
154 // ----------------------------------------------------------------------------
156 // ----------------------------------------------------------------------------
158 class MyThread
: public wxThread
161 MyThread(MyFrame
*frame
);
163 // thread execution starts here
164 virtual void *Entry();
166 // called when the thread exits - whether it terminates normally or is
167 // stopped with Delete() (but not when it is Kill()ed!)
168 virtual void OnExit();
170 // write something to the text control
171 void WriteText(const wxString
& text
);
178 MyThread::MyThread(MyFrame
*frame
)
185 void MyThread::WriteText(const wxString
& text
)
189 // before doing any GUI calls we must ensure that this thread is the only
195 m_frame
->WriteText(msg
);
200 void MyThread::OnExit()
202 wxCriticalSectionLocker
locker(wxGetApp().m_critsect
);
204 wxArrayThread
& threads
= wxGetApp().m_threads
;
205 threads
.Remove(this);
207 if ( threads
.IsEmpty() )
209 // signal the main thread that there are no more threads left if it is
211 if ( wxGetApp().m_waitingUntilAllDone
)
213 wxGetApp().m_waitingUntilAllDone
= FALSE
;
215 wxMutexLocker
lock(wxGetApp().m_mutexAllDone
);
216 wxGetApp().m_condAllDone
.Signal();
221 void *MyThread::Entry()
225 text
.Printf(wxT("Thread 0x%lx started (priority = %u).\n"),
226 GetId(), GetPriority());
228 // wxLogMessage(text); -- test wxLog thread safeness
230 for ( m_count
= 0; m_count
< 10; m_count
++ )
232 // check if we were asked to exit
236 text
.Printf(wxT("[%u] Thread 0x%lx here.\n"), m_count
, GetId());
239 // wxSleep() can't be called from non-GUI thread!
240 wxThread::Sleep(1000);
243 text
.Printf(wxT("Thread 0x%lx finished.\n"), GetId());
245 // wxLogMessage(text); -- test wxLog thread safeness
250 // ----------------------------------------------------------------------------
252 // ----------------------------------------------------------------------------
254 class MyWorkerThread
: public wxThread
257 MyWorkerThread(MyFrame
*frame
);
259 // thread execution starts here
260 virtual void *Entry();
262 // called when the thread exits - whether it terminates normally or is
263 // stopped with Delete() (but not when it is Kill()ed!)
264 virtual void OnExit();
271 MyWorkerThread::MyWorkerThread(MyFrame
*frame
)
278 void MyWorkerThread::OnExit()
282 void *MyWorkerThread::Entry()
284 for ( m_count
= 0; !m_frame
->Cancelled() && (m_count
< 100); m_count
++ )
286 // check if we were asked to exit
290 // create any type of command event here
291 wxCommandEvent
event( wxEVT_COMMAND_MENU_SELECTED
, WORKER_EVENT
);
292 event
.SetInt( m_count
);
294 // send in a thread-safe way
295 wxPostEvent( m_frame
, event
);
297 // wxSleep() can't be called from non-main thread!
298 wxThread::Sleep(200);
301 wxCommandEvent
event( wxEVT_COMMAND_MENU_SELECTED
, WORKER_EVENT
);
302 event
.SetInt(-1); // that's all
303 wxPostEvent( m_frame
, event
);
308 // ----------------------------------------------------------------------------
309 // a thread which simply calls wxExecute
310 // ----------------------------------------------------------------------------
312 class MyExecThread
: public wxThread
315 MyExecThread(const wxChar
*command
) : wxThread(wxTHREAD_JOINABLE
),
321 virtual ExitCode
Entry()
323 return (ExitCode
)EXEC(m_command
);
330 // ----------------------------------------------------------------------------
332 // ----------------------------------------------------------------------------
334 BEGIN_EVENT_TABLE(MyFrame
, wxFrame
)
335 EVT_MENU(THREAD_QUIT
, MyFrame::OnQuit
)
336 EVT_MENU(THREAD_CLEAR
, MyFrame::OnClear
)
337 EVT_MENU(THREAD_START_THREAD
, MyFrame::OnStartThread
)
338 EVT_MENU(THREAD_START_THREADS
, MyFrame::OnStartThreads
)
339 EVT_MENU(THREAD_STOP_THREAD
, MyFrame::OnStopThread
)
340 EVT_MENU(THREAD_PAUSE_THREAD
, MyFrame::OnPauseThread
)
341 EVT_MENU(THREAD_RESUME_THREAD
, MyFrame::OnResumeThread
)
343 EVT_MENU(THREAD_EXEC_MAIN
, MyFrame::OnExecMain
)
344 EVT_MENU(THREAD_EXEC_THREAD
, MyFrame::OnExecThread
)
346 EVT_MENU(THREAD_SHOWCPUS
, MyFrame::OnShowCPUs
)
347 EVT_MENU(THREAD_ABOUT
, MyFrame::OnAbout
)
349 EVT_UPDATE_UI(THREAD_START_WORKER
, MyFrame::OnUpdateWorker
)
350 EVT_MENU(THREAD_START_WORKER
, MyFrame::OnStartWorker
)
351 EVT_MENU(WORKER_EVENT
, MyFrame::OnWorkerEvent
)
353 EVT_IDLE(MyFrame::OnIdle
)
357 : m_condAllDone(m_mutexAllDone
)
359 // the mutex associated with a condition must be initially locked, it will
360 // only be unlocked when we call Wait()
361 m_mutexAllDone
.Lock();
363 m_waitingUntilAllDone
= FALSE
;
368 // the mutex must be unlocked before being destroyed
369 m_mutexAllDone
.Unlock();
372 // `Main program' equivalent, creating windows and returning main app frame
375 // uncomment this to get some debugging messages from the trace code
376 // on the console (or just set WXTRACE env variable to include "thread")
377 //wxLog::AddTraceMask("thread");
379 // Create the main frame window
380 MyFrame
*frame
= new MyFrame((wxFrame
*)NULL
, _T("wxWindows threads sample"),
384 wxMenuBar
*menuBar
= new wxMenuBar
;
386 wxMenu
*menuFile
= new wxMenu
;
387 menuFile
->Append(THREAD_CLEAR
, _T("&Clear log\tCtrl-L"));
388 menuFile
->AppendSeparator();
389 menuFile
->Append(THREAD_QUIT
, _T("E&xit\tAlt-X"));
390 menuBar
->Append(menuFile
, _T("&File"));
392 wxMenu
*menuThread
= new wxMenu
;
393 menuThread
->Append(THREAD_START_THREAD
, _T("&Start a new thread\tCtrl-N"));
394 menuThread
->Append(THREAD_START_THREADS
, _T("Start &many threads at once"));
395 menuThread
->Append(THREAD_STOP_THREAD
, _T("S&top a running thread\tCtrl-S"));
396 menuThread
->AppendSeparator();
397 menuThread
->Append(THREAD_PAUSE_THREAD
, _T("&Pause a running thread\tCtrl-P"));
398 menuThread
->Append(THREAD_RESUME_THREAD
, _T("&Resume suspended thread\tCtrl-R"));
399 menuThread
->AppendSeparator();
400 menuThread
->Append(THREAD_START_WORKER
, _T("Start &worker thread\tCtrl-W"));
401 menuBar
->Append(menuThread
, _T("&Thread"));
403 wxMenu
*menuExec
= new wxMenu
;
404 menuExec
->Append(THREAD_EXEC_MAIN
, _T("&Launch a program from main thread\tF5"));
405 menuExec
->Append(THREAD_EXEC_THREAD
, _T("L&aunch a program from a thread\tCtrl-F5"));
406 menuBar
->Append(menuExec
, _T("&Execute"));
408 wxMenu
*menuHelp
= new wxMenu
;
409 menuHelp
->Append(THREAD_SHOWCPUS
, _T("&Show CPU count"));
410 menuHelp
->AppendSeparator();
411 menuHelp
->Append(THREAD_ABOUT
, _T("&About..."));
412 menuBar
->Append(menuHelp
, _T("&Help"));
414 frame
->SetMenuBar(menuBar
);
424 // My frame constructor
425 MyFrame::MyFrame(wxFrame
*frame
, const wxString
& title
,
426 int x
, int y
, int w
, int h
)
427 : wxFrame(frame
, -1, title
, wxPoint(x
, y
), wxSize(w
, h
))
429 m_nRunning
= m_nCount
= 0;
431 m_dlgProgress
= (wxProgressDialog
*)NULL
;
435 m_txtctrl
= new wxTextCtrl(this, -1, _T(""), wxPoint(0, 0), wxSize(0, 0),
436 wxTE_MULTILINE
| wxTE_READONLY
);
440 MyThread
*MyFrame::CreateThread()
442 MyThread
*thread
= new MyThread(this);
444 if ( thread
->Create() != wxTHREAD_NO_ERROR
)
446 wxLogError(wxT("Can't create thread!"));
449 wxCriticalSectionLocker
enter(wxGetApp().m_critsect
);
450 wxGetApp().m_threads
.Add(thread
);
455 void MyFrame::OnStartThreads(wxCommandEvent
& WXUNUSED(event
) )
457 static long s_num
= 10;
459 s_num
= wxGetNumberFromUser(_T("How many threads to start: "), _T(""),
460 _T("wxThread sample"), s_num
, 1, 10000, this);
468 size_t count
= (size_t)s_num
, n
;
470 wxArrayThread threads
;
472 // first create them all...
473 for ( n
= 0; n
< count
; n
++ )
475 wxThread
*thr
= CreateThread();
477 // we want to show the effect of SetPriority(): the first thread will
478 // have the lowest priority, the second - the highest, all the rest
481 thr
->SetPriority(WXTHREAD_MIN_PRIORITY
);
483 thr
->SetPriority(WXTHREAD_MAX_PRIORITY
);
485 thr
->SetPriority(WXTHREAD_DEFAULT_PRIORITY
);
491 msg
.Printf(wxT("%d new threads created."), count
);
492 SetStatusText(msg
, 1);
494 // ...and then start them
495 for ( n
= 0; n
< count
; n
++ )
501 void MyFrame::OnStartThread(wxCommandEvent
& WXUNUSED(event
) )
503 MyThread
*thread
= CreateThread();
505 if ( thread
->Run() != wxTHREAD_NO_ERROR
)
507 wxLogError(wxT("Can't start thread!"));
510 SetStatusText(_T("New thread started."), 1);
513 void MyFrame::OnStopThread(wxCommandEvent
& WXUNUSED(event
) )
515 wxGetApp().m_critsect
.Enter();
517 // stop the last thread
518 if ( wxGetApp().m_threads
.IsEmpty() )
520 wxLogError(wxT("No thread to stop!"));
522 wxGetApp().m_critsect
.Leave();
526 wxThread
*thread
= wxGetApp().m_threads
.Last();
528 // it's important to leave critical section before calling Delete()
529 // because delete will (implicitly) call OnExit() which also tries
530 // to enter the same crit section - would dead lock.
531 wxGetApp().m_critsect
.Leave();
535 SetStatusText(_T("Thread stopped."), 1);
539 void MyFrame::OnResumeThread(wxCommandEvent
& WXUNUSED(event
) )
541 wxCriticalSectionLocker
enter(wxGetApp().m_critsect
);
543 // resume first suspended thread
544 size_t n
= 0, count
= wxGetApp().m_threads
.Count();
545 while ( n
< count
&& !wxGetApp().m_threads
[n
]->IsPaused() )
550 wxLogError(wxT("No thread to resume!"));
554 wxGetApp().m_threads
[n
]->Resume();
556 SetStatusText(_T("Thread resumed."), 1);
560 void MyFrame::OnPauseThread(wxCommandEvent
& WXUNUSED(event
) )
562 wxCriticalSectionLocker
enter(wxGetApp().m_critsect
);
564 // pause last running thread
565 int n
= wxGetApp().m_threads
.Count() - 1;
566 while ( n
>= 0 && !wxGetApp().m_threads
[n
]->IsRunning() )
571 wxLogError(wxT("No thread to pause!"));
575 wxGetApp().m_threads
[n
]->Pause();
577 SetStatusText(_T("Thread paused."), 1);
581 // set the frame title indicating the current number of threads
582 void MyFrame::OnIdle(wxIdleEvent
&event
)
584 wxCriticalSectionLocker
enter(wxGetApp().m_critsect
);
586 // update the counts of running/total threads
588 nCount
= wxGetApp().m_threads
.Count();
589 for ( size_t n
= 0; n
< nCount
; n
++ )
591 if ( wxGetApp().m_threads
[n
]->IsRunning() )
595 if ( nCount
!= m_nCount
|| nRunning
!= m_nRunning
)
597 m_nRunning
= nRunning
;
600 wxLogStatus(this, wxT("%u threads total, %u running."), nCount
, nRunning
);
602 //else: avoid flicker - don't print anything
605 void MyFrame::OnQuit(wxCommandEvent
& WXUNUSED(event
) )
607 // NB: although the OS will terminate all the threads anyhow when the main
608 // one exits, it's good practice to do it ourselves -- even if it's not
609 // completely trivial in this example
611 // tell all the threads to terminate: note that they can't terminate while
612 // we're deleting them because they will block in their OnExit() -- this is
613 // important as otherwise we might access invalid array elements
615 wxGetApp().m_critsect
.Enter();
617 // check if we have any threads running first
618 const wxArrayThread
& threads
= wxGetApp().m_threads
;
619 size_t count
= threads
.GetCount();
623 // we do, ask them to stop
624 for ( size_t n
= 0; n
< count
; n
++ )
626 threads
[n
]->Delete();
629 // set the flag for MyThread::OnExit()
630 wxGetApp().m_waitingUntilAllDone
= TRUE
;
633 wxGetApp().m_critsect
.Leave();
637 // now wait for them to really terminate but leave the GUI mutex
638 // before doing it as otherwise we might dead lock
641 wxGetApp().m_condAllDone
.Wait();
645 //else: no threads to terminate, no condition to wait for
651 void MyFrame::OnExecMain(wxCommandEvent
& WXUNUSED(event
))
653 wxLogMessage(wxT("The exit code from the main program is %ld"),
654 EXEC(_T("/bin/echo \"main program\"")));
657 void MyFrame::OnExecThread(wxCommandEvent
& WXUNUSED(event
))
659 MyExecThread
thread(wxT("/bin/echo \"child thread\""));
662 wxLogMessage(wxT("The exit code from a child thread is %ld"),
663 (long)thread
.Wait());
666 void MyFrame::OnShowCPUs(wxCommandEvent
& WXUNUSED(event
))
670 int nCPUs
= wxThread::GetCPUCount();
674 msg
= _T("Unknown number of CPUs");
678 msg
= _T("WARNING: you're running without any CPUs!");
682 msg
= _T("This system only has one CPU.");
686 msg
.Printf(wxT("This system has %d CPUs"), nCPUs
);
692 void MyFrame::OnAbout(wxCommandEvent
& WXUNUSED(event
) )
694 wxMessageDialog
dialog(this,
695 _T("wxWindows multithreaded application sample\n")
696 _T("(c) 1998 Julian Smart, Guilhem Lavaux\n")
697 _T("(c) 1999 Vadim Zeitlin\n")
698 _T("(c) 2000 Robert Roebling"),
699 _T("About wxThread sample"),
700 wxOK
| wxICON_INFORMATION
);
705 void MyFrame::OnClear(wxCommandEvent
& WXUNUSED(event
))
710 void MyFrame::OnUpdateWorker(wxUpdateUIEvent
& event
)
712 event
.Enable( m_dlgProgress
== NULL
);
715 void MyFrame::OnStartWorker(wxCommandEvent
& WXUNUSED(event
))
717 MyWorkerThread
*thread
= new MyWorkerThread(this);
719 if ( thread
->Create() != wxTHREAD_NO_ERROR
)
721 wxLogError(wxT("Can't create thread!"));
724 m_dlgProgress
= new wxProgressDialog
726 _T("Progress dialog"),
727 _T("Wait until the thread terminates or press [Cancel]"),
733 wxPD_ESTIMATED_TIME
|
737 // thread is not running yet, no need for crit sect
743 void MyFrame::OnWorkerEvent(wxCommandEvent
& event
)
746 WriteText( _T("Got message from worker thread: ") );
747 WriteText( event
.GetString() );
748 WriteText( _T("\n") );
750 int n
= event
.GetInt();
753 m_dlgProgress
->Destroy();
754 m_dlgProgress
= (wxProgressDialog
*)NULL
;
756 // the dialog is aborted because the event came from another thread, so
757 // we may need to wake up the main event loop for the dialog to be
763 if ( !m_dlgProgress
->Update(n
) )
765 wxCriticalSectionLocker
lock(m_critsectWork
);
773 bool MyFrame::Cancelled()
775 wxCriticalSectionLocker
lock(m_critsectWork
);