1 /////////////////////////////////////////////////////////////////////////////
3 // Purpose: wxWindows thread sample
4 // Author: Julian Smart(minimal)/Guilhem Lavaux(thread test)
8 // Copyright: (c) Julian Smart, Markus Holzem, Guilhem Lavaux
9 // Licence: wxWindows license
10 /////////////////////////////////////////////////////////////////////////////
13 TODO: use worker threads to update progress controls instead of writing
14 messages - it will be more visual
17 // For compilers that support precompilation, includes "wx/wx.h".
18 #include "wx/wxprec.h"
29 #error "This sample requires thread support!"
30 #endif // wxUSE_THREADS
32 #include "wx/thread.h"
33 #include "wx/dynarray.h"
36 #include "wx/progdlg.h"
39 #define EXEC(cmd) wxExecute((cmd), wxEXEC_SYNC)
41 #define EXEC(cmd) system(cmd)
45 WX_DEFINE_ARRAY(wxThread
*, wxArrayThread
);
47 // Define a new application type
48 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
;
62 // Create a new application object
65 // Define a new frame type
66 class MyFrame
: public wxFrame
70 MyFrame(wxFrame
*frame
, const wxString
& title
, int x
, int y
, int w
, int h
);
73 void WriteText(const wxString
& text
) { m_txtctrl
->WriteText(text
); }
75 // accessors for MyWorkerThread (called in its context!)
79 void OnQuit(wxCommandEvent
& event
);
80 void OnClear(wxCommandEvent
& event
);
82 void OnStartThread(wxCommandEvent
& event
);
83 void OnStartThreads(wxCommandEvent
& event
);
84 void OnStopThread(wxCommandEvent
& event
);
85 void OnPauseThread(wxCommandEvent
& event
);
86 void OnResumeThread(wxCommandEvent
& event
);
88 void OnStartWorker(wxCommandEvent
& event
);
89 void OnWorkerEvent(wxCommandEvent
& event
);
90 void OnUpdateWorker(wxUpdateUIEvent
& event
);
92 void OnExecMain(wxCommandEvent
& event
);
93 void OnExecThread(wxCommandEvent
& event
);
95 void OnShowCPUs(wxCommandEvent
& event
);
96 void OnAbout(wxCommandEvent
& event
);
98 void OnIdle(wxIdleEvent
&event
);
101 // helper function - creates a new thread (but doesn't run it)
102 MyThread
*CreateThread();
104 // just some place to put our messages in
105 wxTextCtrl
*m_txtctrl
;
107 // remember the number of running threads and total number of threads
108 size_t m_nRunning
, m_nCount
;
110 // the progress dialog which we show while worker thread is running
111 wxProgressDialog
*m_dlgProgress
;
113 // was the worker thread cancelled by user?
116 // protects m_cancelled
117 wxCriticalSection m_critsectWork
;
119 DECLARE_EVENT_TABLE()
122 // ID for the menu commands
128 THREAD_START_THREAD
= 201,
129 THREAD_START_THREADS
,
132 THREAD_RESUME_THREAD
,
141 WORKER_EVENT
// this one gets sent from the worker thread
144 // ----------------------------------------------------------------------------
146 // ----------------------------------------------------------------------------
148 class MyThread
: public wxThread
151 MyThread(MyFrame
*frame
);
153 // thread execution starts here
154 virtual void *Entry();
156 // called when the thread exits - whether it terminates normally or is
157 // stopped with Delete() (but not when it is Kill()ed!)
158 virtual void OnExit();
160 // write something to the text control
161 void WriteText(const wxString
& text
);
168 MyThread::MyThread(MyFrame
*frame
)
175 void MyThread::WriteText(const wxString
& text
)
179 // before doing any GUI calls we must ensure that this thread is the only
185 m_frame
->WriteText(msg
);
190 void MyThread::OnExit()
192 wxCriticalSectionLocker
locker(wxGetApp().m_critsect
);
194 wxGetApp().m_threads
.Remove(this);
197 void *MyThread::Entry()
201 text
.Printf(wxT("Thread 0x%x started (priority = %d).\n"),
202 GetId(), GetPriority());
204 // wxLogMessage(text); -- test wxLog thread safeness
206 for ( m_count
= 0; m_count
< 10; m_count
++ )
208 // check if we were asked to exit
212 text
.Printf(wxT("[%u] Thread 0x%x here.\n"), m_count
, GetId());
215 // wxSleep() can't be called from non-GUI thread!
216 wxThread::Sleep(1000);
219 text
.Printf(wxT("Thread 0x%x finished.\n"), GetId());
221 // wxLogMessage(text); -- test wxLog thread safeness
226 // ----------------------------------------------------------------------------
228 // ----------------------------------------------------------------------------
230 class MyWorkerThread
: public wxThread
233 MyWorkerThread(MyFrame
*frame
);
235 // thread execution starts here
236 virtual void *Entry();
238 // called when the thread exits - whether it terminates normally or is
239 // stopped with Delete() (but not when it is Kill()ed!)
240 virtual void OnExit();
247 MyWorkerThread::MyWorkerThread(MyFrame
*frame
)
254 void MyWorkerThread::OnExit()
258 void *MyWorkerThread::Entry()
260 for ( m_count
= 0; !m_frame
->Cancelled() && (m_count
< 100); m_count
++ )
262 // check if we were asked to exit
266 // create any type of command event here
267 wxCommandEvent
event( wxEVT_COMMAND_MENU_SELECTED
, WORKER_EVENT
);
268 event
.SetInt( m_count
);
270 // send in a thread-safe way
271 wxPostEvent( m_frame
, event
);
273 // wxSleep() can't be called from non-main thread!
274 wxThread::Sleep(200);
277 wxCommandEvent
event( wxEVT_COMMAND_MENU_SELECTED
, WORKER_EVENT
);
278 event
.SetInt(-1); // that's all
279 wxPostEvent( m_frame
, event
);
284 // ----------------------------------------------------------------------------
285 // a thread which simply calls wxExecute
286 // ----------------------------------------------------------------------------
288 class MyExecThread
: public wxThread
291 MyExecThread(const wxChar
*command
) : wxThread(wxTHREAD_JOINABLE
),
297 virtual ExitCode
Entry()
299 return (ExitCode
)EXEC(m_command
);
306 // ----------------------------------------------------------------------------
308 // ----------------------------------------------------------------------------
310 BEGIN_EVENT_TABLE(MyFrame
, wxFrame
)
311 EVT_MENU(THREAD_QUIT
, MyFrame::OnQuit
)
312 EVT_MENU(THREAD_CLEAR
, MyFrame::OnClear
)
313 EVT_MENU(THREAD_START_THREAD
, MyFrame::OnStartThread
)
314 EVT_MENU(THREAD_START_THREADS
, MyFrame::OnStartThreads
)
315 EVT_MENU(THREAD_STOP_THREAD
, MyFrame::OnStopThread
)
316 EVT_MENU(THREAD_PAUSE_THREAD
, MyFrame::OnPauseThread
)
317 EVT_MENU(THREAD_RESUME_THREAD
, MyFrame::OnResumeThread
)
319 EVT_MENU(THREAD_EXEC_MAIN
, MyFrame::OnExecMain
)
320 EVT_MENU(THREAD_EXEC_THREAD
, MyFrame::OnExecThread
)
322 EVT_MENU(THREAD_SHOWCPUS
, MyFrame::OnShowCPUs
)
323 EVT_MENU(THREAD_ABOUT
, MyFrame::OnAbout
)
325 EVT_UPDATE_UI(THREAD_START_WORKER
, MyFrame::OnUpdateWorker
)
326 EVT_MENU(THREAD_START_WORKER
, MyFrame::OnStartWorker
)
327 EVT_MENU(WORKER_EVENT
, MyFrame::OnWorkerEvent
)
329 EVT_IDLE(MyFrame::OnIdle
)
332 // `Main program' equivalent, creating windows and returning main app frame
335 // uncomment this to get some debugging messages from the trace code
336 // on the console (or just set WXTRACE env variable to include "thread")
337 //wxLog::AddTraceMask("thread");
339 // Create the main frame window
340 MyFrame
*frame
= new MyFrame((wxFrame
*)NULL
, "wxWindows threads sample",
344 wxMenuBar
*menuBar
= new wxMenuBar
;
346 wxMenu
*menuFile
= new wxMenu
;
347 menuFile
->Append(THREAD_CLEAR
, "&Clear log\tCtrl-L");
348 menuFile
->AppendSeparator();
349 menuFile
->Append(THREAD_QUIT
, "E&xit\tAlt-X");
350 menuBar
->Append(menuFile
, "&File");
352 wxMenu
*menuThread
= new wxMenu
;
353 menuThread
->Append(THREAD_START_THREAD
, "&Start a new thread\tCtrl-N");
354 menuThread
->Append(THREAD_START_THREADS
, "Start &many threads at once");
355 menuThread
->Append(THREAD_STOP_THREAD
, "S&top a running thread\tCtrl-S");
356 menuThread
->AppendSeparator();
357 menuThread
->Append(THREAD_PAUSE_THREAD
, "&Pause a running thread\tCtrl-P");
358 menuThread
->Append(THREAD_RESUME_THREAD
, "&Resume suspended thread\tCtrl-R");
359 menuThread
->AppendSeparator();
360 menuThread
->Append(THREAD_START_WORKER
, "Start &worker thread\tCtrl-W");
361 menuBar
->Append(menuThread
, "&Thread");
363 wxMenu
*menuExec
= new wxMenu
;
364 menuExec
->Append(THREAD_EXEC_MAIN
, "&Launch a program from main thread\tF5");
365 menuExec
->Append(THREAD_EXEC_THREAD
, "L&aunch a program from a thread\tCtrl-F5");
366 menuBar
->Append(menuExec
, "&Execute");
368 wxMenu
*menuHelp
= new wxMenu
;
369 menuHelp
->Append(THREAD_SHOWCPUS
, "&Show CPU count");
370 menuHelp
->AppendSeparator();
371 menuHelp
->Append(THREAD_ABOUT
, "&About...");
372 menuBar
->Append(menuHelp
, "&Help");
374 frame
->SetMenuBar(menuBar
);
384 // My frame constructor
385 MyFrame::MyFrame(wxFrame
*frame
, const wxString
& title
,
386 int x
, int y
, int w
, int h
)
387 : wxFrame(frame
, -1, title
, wxPoint(x
, y
), wxSize(w
, h
))
389 m_nRunning
= m_nCount
= 0;
391 m_dlgProgress
= (wxProgressDialog
*)NULL
;
395 m_txtctrl
= new wxTextCtrl(this, -1, "", wxPoint(0, 0), wxSize(0, 0),
396 wxTE_MULTILINE
| wxTE_READONLY
);
400 MyThread
*MyFrame::CreateThread()
402 MyThread
*thread
= new MyThread(this);
404 if ( thread
->Create() != wxTHREAD_NO_ERROR
)
406 wxLogError(wxT("Can't create thread!"));
409 wxCriticalSectionLocker
enter(wxGetApp().m_critsect
);
410 wxGetApp().m_threads
.Add(thread
);
415 void MyFrame::OnStartThreads(wxCommandEvent
& WXUNUSED(event
) )
417 static long s_num
= 10;
419 s_num
= wxGetNumberFromUser("How many threads to start: ", "",
420 "wxThread sample", s_num
, 1, 10000, this);
428 size_t count
= (size_t)s_num
, n
;
430 wxArrayThread threads
;
432 // first create them all...
433 for ( n
= 0; n
< count
; n
++ )
435 wxThread
*thr
= CreateThread();
437 // we want to show the effect of SetPriority(): the first thread will
438 // have the lowest priority, the second - the highest, all the rest
441 thr
->SetPriority(WXTHREAD_MIN_PRIORITY
);
443 thr
->SetPriority(WXTHREAD_MAX_PRIORITY
);
445 thr
->SetPriority(WXTHREAD_DEFAULT_PRIORITY
);
451 msg
.Printf(wxT("%d new threads created."), count
);
452 SetStatusText(msg
, 1);
454 // ...and then start them
455 for ( n
= 0; n
< count
; n
++ )
461 void MyFrame::OnStartThread(wxCommandEvent
& WXUNUSED(event
) )
463 MyThread
*thread
= CreateThread();
465 if ( thread
->Run() != wxTHREAD_NO_ERROR
)
467 wxLogError(wxT("Can't start thread!"));
470 SetStatusText("New thread started.", 1);
473 void MyFrame::OnStopThread(wxCommandEvent
& WXUNUSED(event
) )
475 wxGetApp().m_critsect
.Enter();
477 // stop the last thread
478 if ( wxGetApp().m_threads
.IsEmpty() )
480 wxLogError(wxT("No thread to stop!"));
482 wxGetApp().m_critsect
.Leave();
486 wxThread
*thread
= wxGetApp().m_threads
.Last();
488 // it's important to leave critical section before calling Delete()
489 // because delete will (implicitly) call OnExit() which also tries
490 // to enter the same crit section - would dead lock.
491 wxGetApp().m_critsect
.Leave();
495 SetStatusText("Thread stopped.", 1);
499 void MyFrame::OnResumeThread(wxCommandEvent
& WXUNUSED(event
) )
501 wxCriticalSectionLocker
enter(wxGetApp().m_critsect
);
503 // resume first suspended thread
504 size_t n
= 0, count
= wxGetApp().m_threads
.Count();
505 while ( n
< count
&& !wxGetApp().m_threads
[n
]->IsPaused() )
510 wxLogError(wxT("No thread to resume!"));
514 wxGetApp().m_threads
[n
]->Resume();
516 SetStatusText("Thread resumed.", 1);
520 void MyFrame::OnPauseThread(wxCommandEvent
& WXUNUSED(event
) )
522 wxCriticalSectionLocker
enter(wxGetApp().m_critsect
);
524 // pause last running thread
525 int n
= wxGetApp().m_threads
.Count() - 1;
526 while ( n
>= 0 && !wxGetApp().m_threads
[n
]->IsRunning() )
531 wxLogError(wxT("No thread to pause!"));
535 wxGetApp().m_threads
[n
]->Pause();
537 SetStatusText("Thread paused.", 1);
541 // set the frame title indicating the current number of threads
542 void MyFrame::OnIdle(wxIdleEvent
&event
)
544 // update the counts of running/total threads
546 nCount
= wxGetApp().m_threads
.Count();
547 for ( size_t n
= 0; n
< nCount
; n
++ )
549 if ( wxGetApp().m_threads
[n
]->IsRunning() )
553 if ( nCount
!= m_nCount
|| nRunning
!= m_nRunning
)
555 m_nRunning
= nRunning
;
558 wxLogStatus(this, wxT("%u threads total, %u running."), nCount
, nRunning
);
560 //else: avoid flicker - don't print anything
563 void MyFrame::OnQuit(wxCommandEvent
& WXUNUSED(event
) )
565 size_t count
= wxGetApp().m_threads
.Count();
566 for ( size_t i
= 0; i
< count
; i
++ )
568 wxGetApp().m_threads
[0]->Delete();
574 void MyFrame::OnExecMain(wxCommandEvent
& WXUNUSED(event
))
576 wxLogMessage("The exit code from the main program is %ld",
577 EXEC("/bin/echo \"main program\""));
580 void MyFrame::OnExecThread(wxCommandEvent
& WXUNUSED(event
))
582 MyExecThread
thread("/bin/echo \"child thread\"");
585 wxLogMessage("The exit code from a child thread is %ld",
586 (long)thread
.Wait());
589 void MyFrame::OnShowCPUs(wxCommandEvent
& WXUNUSED(event
))
593 int nCPUs
= wxThread::GetCPUCount();
597 msg
= "Unknown number of CPUs";
601 msg
= "WARNING: you're running without any CPUs!";
605 msg
= "This system only has one CPU.";
609 msg
.Printf("This system has %d CPUs", nCPUs
);
615 void MyFrame::OnAbout(wxCommandEvent
& WXUNUSED(event
) )
617 wxMessageDialog
dialog(this, "wxWindows multithreaded application sample\n"
618 "(c) 1998 Julian Smart, Guilhem Lavaux\n"
619 "(c) 1999 Vadim Zeitlin\n"
620 "(c) 2000 Robert Roebling",
621 "About wxThread sample",
622 wxOK
| wxICON_INFORMATION
);
627 void MyFrame::OnClear(wxCommandEvent
& WXUNUSED(event
))
632 void MyFrame::OnUpdateWorker(wxUpdateUIEvent
& event
)
634 event
.Enable( m_dlgProgress
== NULL
);
637 void MyFrame::OnStartWorker(wxCommandEvent
& WXUNUSED(event
))
639 MyWorkerThread
*thread
= new MyWorkerThread(this);
641 if ( thread
->Create() != wxTHREAD_NO_ERROR
)
643 wxLogError(wxT("Can't create thread!"));
646 m_dlgProgress
= new wxProgressDialog
649 "Wait until the thread terminates or press [Cancel]",
655 wxPD_ESTIMATED_TIME
|
659 // thread is not running yet, no need for crit sect
665 void MyFrame::OnWorkerEvent(wxCommandEvent
& event
)
668 WriteText( "Got message from worker thread: " );
669 WriteText( event
.GetString() );
672 int n
= event
.GetInt();
675 m_dlgProgress
->Destroy();
676 m_dlgProgress
= (wxProgressDialog
*)NULL
;
678 // the dialog is aborted because the event came from another thread, so
679 // we may need to wake up the main event loop for the dialog to be
685 if ( !m_dlgProgress
->Update(n
) )
687 wxCriticalSectionLocker
lock(m_critsectWork
);
695 bool MyFrame::Cancelled()
697 wxCriticalSectionLocker
lock(m_critsectWork
);