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"
40 #define EXEC(cmd) wxExecute((cmd), wxEXEC_SYNC)
42 #define EXEC(cmd) system(cmd)
46 WX_DEFINE_ARRAY(wxThread
*, wxArrayThread
);
48 // Define a new application type
49 class MyApp
: public wxApp
52 virtual bool OnInit();
55 // all the threads currently alive - as soon as the thread terminates, it's
56 // removed from the array
57 wxArrayThread m_threads
;
59 // crit section protects access to all of the arrays below
60 wxCriticalSection m_critsect
;
63 // Create a new application object
66 // Define a new frame type
67 class MyFrame
: public wxFrame
71 MyFrame(wxFrame
*frame
, const wxString
& title
, int x
, int y
, int w
, int h
);
74 void WriteText(const wxString
& text
) { m_txtctrl
->WriteText(text
); }
76 // accessors for MyWorkerThread (called in its context!)
80 void OnQuit(wxCommandEvent
& event
);
81 void OnClear(wxCommandEvent
& event
);
83 void OnStartThread(wxCommandEvent
& event
);
84 void OnStartThreads(wxCommandEvent
& event
);
85 void OnStopThread(wxCommandEvent
& event
);
86 void OnPauseThread(wxCommandEvent
& event
);
87 void OnResumeThread(wxCommandEvent
& event
);
89 void OnStartWorker(wxCommandEvent
& event
);
90 void OnWorkerEvent(wxCommandEvent
& event
);
91 void OnUpdateWorker(wxUpdateUIEvent
& event
);
93 void OnExecMain(wxCommandEvent
& event
);
94 void OnExecThread(wxCommandEvent
& event
);
96 void OnShowCPUs(wxCommandEvent
& event
);
97 void OnAbout(wxCommandEvent
& event
);
99 void OnIdle(wxIdleEvent
&event
);
102 // helper function - creates a new thread (but doesn't run it)
103 MyThread
*CreateThread();
105 // just some place to put our messages in
106 wxTextCtrl
*m_txtctrl
;
108 // remember the number of running threads and total number of threads
109 size_t m_nRunning
, m_nCount
;
111 // the progress dialog which we show while worker thread is running
112 wxProgressDialog
*m_dlgProgress
;
114 // was the worker thread cancelled by user?
117 // protects m_cancelled
118 wxCriticalSection m_critsectWork
;
120 DECLARE_EVENT_TABLE()
123 // ID for the menu commands
129 THREAD_START_THREAD
= 201,
130 THREAD_START_THREADS
,
133 THREAD_RESUME_THREAD
,
142 WORKER_EVENT
// this one gets sent from the worker thread
145 // ----------------------------------------------------------------------------
147 // ----------------------------------------------------------------------------
149 class MyThread
: public wxThread
152 MyThread(MyFrame
*frame
);
154 // thread execution starts here
155 virtual void *Entry();
157 // called when the thread exits - whether it terminates normally or is
158 // stopped with Delete() (but not when it is Kill()ed!)
159 virtual void OnExit();
161 // write something to the text control
162 void WriteText(const wxString
& text
);
169 MyThread::MyThread(MyFrame
*frame
)
176 void MyThread::WriteText(const wxString
& text
)
180 // before doing any GUI calls we must ensure that this thread is the only
186 m_frame
->WriteText(msg
);
191 void MyThread::OnExit()
193 wxCriticalSectionLocker
locker(wxGetApp().m_critsect
);
195 wxGetApp().m_threads
.Remove(this);
198 void *MyThread::Entry()
202 text
.Printf(wxT("Thread 0x%x started (priority = %d).\n"),
203 GetId(), GetPriority());
205 // wxLogMessage(text); -- test wxLog thread safeness
207 for ( m_count
= 0; m_count
< 10; m_count
++ )
209 // check if we were asked to exit
213 text
.Printf(wxT("[%u] Thread 0x%x here.\n"), m_count
, GetId());
216 // wxSleep() can't be called from non-GUI thread!
217 wxThread::Sleep(1000);
220 text
.Printf(wxT("Thread 0x%x finished.\n"), GetId());
222 // wxLogMessage(text); -- test wxLog thread safeness
227 // ----------------------------------------------------------------------------
229 // ----------------------------------------------------------------------------
231 class MyWorkerThread
: public wxThread
234 MyWorkerThread(MyFrame
*frame
);
236 // thread execution starts here
237 virtual void *Entry();
239 // called when the thread exits - whether it terminates normally or is
240 // stopped with Delete() (but not when it is Kill()ed!)
241 virtual void OnExit();
248 MyWorkerThread::MyWorkerThread(MyFrame
*frame
)
255 void MyWorkerThread::OnExit()
259 void *MyWorkerThread::Entry()
261 for ( m_count
= 0; !m_frame
->Cancelled() && (m_count
< 100); m_count
++ )
263 // check if we were asked to exit
267 // create any type of command event here
268 wxCommandEvent
event( wxEVT_COMMAND_MENU_SELECTED
, WORKER_EVENT
);
269 event
.SetInt( m_count
);
271 // send in a thread-safe way
272 wxPostEvent( m_frame
, event
);
274 // wxSleep() can't be called from non-main thread!
275 wxThread::Sleep(200);
278 wxCommandEvent
event( wxEVT_COMMAND_MENU_SELECTED
, WORKER_EVENT
);
279 event
.SetInt(-1); // that's all
280 wxPostEvent( m_frame
, event
);
285 // ----------------------------------------------------------------------------
286 // a thread which simply calls wxExecute
287 // ----------------------------------------------------------------------------
289 class MyExecThread
: public wxThread
292 MyExecThread(const wxChar
*command
) : wxThread(wxTHREAD_JOINABLE
),
298 virtual ExitCode
Entry()
300 return (ExitCode
)EXEC(m_command
);
307 // ----------------------------------------------------------------------------
309 // ----------------------------------------------------------------------------
311 BEGIN_EVENT_TABLE(MyFrame
, wxFrame
)
312 EVT_MENU(THREAD_QUIT
, MyFrame::OnQuit
)
313 EVT_MENU(THREAD_CLEAR
, MyFrame::OnClear
)
314 EVT_MENU(THREAD_START_THREAD
, MyFrame::OnStartThread
)
315 EVT_MENU(THREAD_START_THREADS
, MyFrame::OnStartThreads
)
316 EVT_MENU(THREAD_STOP_THREAD
, MyFrame::OnStopThread
)
317 EVT_MENU(THREAD_PAUSE_THREAD
, MyFrame::OnPauseThread
)
318 EVT_MENU(THREAD_RESUME_THREAD
, MyFrame::OnResumeThread
)
320 EVT_MENU(THREAD_EXEC_MAIN
, MyFrame::OnExecMain
)
321 EVT_MENU(THREAD_EXEC_THREAD
, MyFrame::OnExecThread
)
323 EVT_MENU(THREAD_SHOWCPUS
, MyFrame::OnShowCPUs
)
324 EVT_MENU(THREAD_ABOUT
, MyFrame::OnAbout
)
326 EVT_UPDATE_UI(THREAD_START_WORKER
, MyFrame::OnUpdateWorker
)
327 EVT_MENU(THREAD_START_WORKER
, MyFrame::OnStartWorker
)
328 EVT_MENU(WORKER_EVENT
, MyFrame::OnWorkerEvent
)
330 EVT_IDLE(MyFrame::OnIdle
)
333 // `Main program' equivalent, creating windows and returning main app frame
336 // uncomment this to get some debugging messages from the trace code
337 // on the console (or just set WXTRACE env variable to include "thread")
338 //wxLog::AddTraceMask("thread");
340 // Create the main frame window
341 MyFrame
*frame
= new MyFrame((wxFrame
*)NULL
, "wxWindows threads sample",
345 wxMenuBar
*menuBar
= new wxMenuBar
;
347 wxMenu
*menuFile
= new wxMenu
;
348 menuFile
->Append(THREAD_CLEAR
, "&Clear log\tCtrl-L");
349 menuFile
->AppendSeparator();
350 menuFile
->Append(THREAD_QUIT
, "E&xit\tAlt-X");
351 menuBar
->Append(menuFile
, "&File");
353 wxMenu
*menuThread
= new wxMenu
;
354 menuThread
->Append(THREAD_START_THREAD
, "&Start a new thread\tCtrl-N");
355 menuThread
->Append(THREAD_START_THREADS
, "Start &many threads at once");
356 menuThread
->Append(THREAD_STOP_THREAD
, "S&top a running thread\tCtrl-S");
357 menuThread
->AppendSeparator();
358 menuThread
->Append(THREAD_PAUSE_THREAD
, "&Pause a running thread\tCtrl-P");
359 menuThread
->Append(THREAD_RESUME_THREAD
, "&Resume suspended thread\tCtrl-R");
360 menuThread
->AppendSeparator();
361 menuThread
->Append(THREAD_START_WORKER
, "Start &worker thread\tCtrl-W");
362 menuBar
->Append(menuThread
, "&Thread");
364 wxMenu
*menuExec
= new wxMenu
;
365 menuExec
->Append(THREAD_EXEC_MAIN
, "&Launch a program from main thread\tF5");
366 menuExec
->Append(THREAD_EXEC_THREAD
, "L&aunch a program from a thread\tCtrl-F5");
367 menuBar
->Append(menuExec
, "&Execute");
369 wxMenu
*menuHelp
= new wxMenu
;
370 menuHelp
->Append(THREAD_SHOWCPUS
, "&Show CPU count");
371 menuHelp
->AppendSeparator();
372 menuHelp
->Append(THREAD_ABOUT
, "&About...");
373 menuBar
->Append(menuHelp
, "&Help");
375 frame
->SetMenuBar(menuBar
);
385 // My frame constructor
386 MyFrame::MyFrame(wxFrame
*frame
, const wxString
& title
,
387 int x
, int y
, int w
, int h
)
388 : wxFrame(frame
, -1, title
, wxPoint(x
, y
), wxSize(w
, h
))
390 m_nRunning
= m_nCount
= 0;
392 m_dlgProgress
= (wxProgressDialog
*)NULL
;
396 m_txtctrl
= new wxTextCtrl(this, -1, "", wxPoint(0, 0), wxSize(0, 0),
397 wxTE_MULTILINE
| wxTE_READONLY
);
401 MyThread
*MyFrame::CreateThread()
403 MyThread
*thread
= new MyThread(this);
405 if ( thread
->Create() != wxTHREAD_NO_ERROR
)
407 wxLogError(wxT("Can't create thread!"));
410 wxCriticalSectionLocker
enter(wxGetApp().m_critsect
);
411 wxGetApp().m_threads
.Add(thread
);
416 void MyFrame::OnStartThreads(wxCommandEvent
& WXUNUSED(event
) )
418 static long s_num
= 10;
420 s_num
= wxGetNumberFromUser("How many threads to start: ", "",
421 "wxThread sample", s_num
, 1, 10000, this);
429 size_t count
= (size_t)s_num
, n
;
431 wxArrayThread threads
;
433 // first create them all...
434 for ( n
= 0; n
< count
; n
++ )
436 wxThread
*thr
= CreateThread();
438 // we want to show the effect of SetPriority(): the first thread will
439 // have the lowest priority, the second - the highest, all the rest
442 thr
->SetPriority(WXTHREAD_MIN_PRIORITY
);
444 thr
->SetPriority(WXTHREAD_MAX_PRIORITY
);
446 thr
->SetPriority(WXTHREAD_DEFAULT_PRIORITY
);
452 msg
.Printf(wxT("%d new threads created."), count
);
453 SetStatusText(msg
, 1);
455 // ...and then start them
456 for ( n
= 0; n
< count
; n
++ )
462 void MyFrame::OnStartThread(wxCommandEvent
& WXUNUSED(event
) )
464 MyThread
*thread
= CreateThread();
466 if ( thread
->Run() != wxTHREAD_NO_ERROR
)
468 wxLogError(wxT("Can't start thread!"));
471 SetStatusText("New thread started.", 1);
474 void MyFrame::OnStopThread(wxCommandEvent
& WXUNUSED(event
) )
476 wxGetApp().m_critsect
.Enter();
478 // stop the last thread
479 if ( wxGetApp().m_threads
.IsEmpty() )
481 wxLogError(wxT("No thread to stop!"));
483 wxGetApp().m_critsect
.Leave();
487 wxThread
*thread
= wxGetApp().m_threads
.Last();
489 // it's important to leave critical section before calling Delete()
490 // because delete will (implicitly) call OnExit() which also tries
491 // to enter the same crit section - would dead lock.
492 wxGetApp().m_critsect
.Leave();
496 SetStatusText("Thread stopped.", 1);
500 void MyFrame::OnResumeThread(wxCommandEvent
& WXUNUSED(event
) )
502 wxCriticalSectionLocker
enter(wxGetApp().m_critsect
);
504 // resume first suspended thread
505 size_t n
= 0, count
= wxGetApp().m_threads
.Count();
506 while ( n
< count
&& !wxGetApp().m_threads
[n
]->IsPaused() )
511 wxLogError(wxT("No thread to resume!"));
515 wxGetApp().m_threads
[n
]->Resume();
517 SetStatusText("Thread resumed.", 1);
521 void MyFrame::OnPauseThread(wxCommandEvent
& WXUNUSED(event
) )
523 wxCriticalSectionLocker
enter(wxGetApp().m_critsect
);
525 // pause last running thread
526 int n
= wxGetApp().m_threads
.Count() - 1;
527 while ( n
>= 0 && !wxGetApp().m_threads
[n
]->IsRunning() )
532 wxLogError(wxT("No thread to pause!"));
536 wxGetApp().m_threads
[n
]->Pause();
538 SetStatusText("Thread paused.", 1);
542 // set the frame title indicating the current number of threads
543 void MyFrame::OnIdle(wxIdleEvent
&event
)
545 // update the counts of running/total threads
547 nCount
= wxGetApp().m_threads
.Count();
548 for ( size_t n
= 0; n
< nCount
; n
++ )
550 if ( wxGetApp().m_threads
[n
]->IsRunning() )
554 if ( nCount
!= m_nCount
|| nRunning
!= m_nRunning
)
556 m_nRunning
= nRunning
;
559 wxLogStatus(this, wxT("%u threads total, %u running."), nCount
, nRunning
);
561 //else: avoid flicker - don't print anything
564 void MyFrame::OnQuit(wxCommandEvent
& WXUNUSED(event
) )
566 size_t count
= wxGetApp().m_threads
.Count();
567 for ( size_t i
= 0; i
< count
; i
++ )
569 wxGetApp().m_threads
[0]->Delete();
575 void MyFrame::OnExecMain(wxCommandEvent
& WXUNUSED(event
))
577 wxLogMessage("The exit code from the main program is %ld",
578 EXEC("/bin/echo \"main program\""));
581 void MyFrame::OnExecThread(wxCommandEvent
& WXUNUSED(event
))
583 MyExecThread
thread("/bin/echo \"child thread\"");
586 wxLogMessage("The exit code from a child thread is %ld",
587 (long)thread
.Wait());
590 void MyFrame::OnShowCPUs(wxCommandEvent
& WXUNUSED(event
))
594 int nCPUs
= wxThread::GetCPUCount();
598 msg
= "Unknown number of CPUs";
602 msg
= "WARNING: you're running without any CPUs!";
606 msg
= "This system only has one CPU.";
610 msg
.Printf("This system has %d CPUs", nCPUs
);
616 void MyFrame::OnAbout(wxCommandEvent
& WXUNUSED(event
) )
618 wxMessageDialog
dialog(this, "wxWindows multithreaded application sample\n"
619 "(c) 1998 Julian Smart, Guilhem Lavaux\n"
620 "(c) 1999 Vadim Zeitlin\n"
621 "(c) 2000 Robert Roebling",
622 "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!"));
647 m_dlgProgress
= new wxProgressDialog
650 "Wait until the thread terminates or press [Cancel]",
656 wxPD_ESTIMATED_TIME
|
660 // thread is not running yet, no need for crit sect
666 void MyFrame::OnWorkerEvent(wxCommandEvent
& event
)
669 WriteText( "Got message from worker thread: " );
670 WriteText( event
.GetString() );
673 int n
= event
.GetInt();
676 m_dlgProgress
->Destroy();
677 m_dlgProgress
= (wxProgressDialog
*)NULL
;
679 // the dialog is aborted because the event came from another thread, so
680 // we may need to wake up the main event loop for the dialog to be
686 if ( !m_dlgProgress
->Update(n
) )
688 wxCriticalSectionLocker
lock(m_critsectWork
);
696 bool MyFrame::Cancelled()
698 wxCriticalSectionLocker
lock(m_critsectWork
);