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"
38 // uncomment this to get some debugging messages from the trace code
42 WX_DEFINE_ARRAY(wxThread
*, wxArrayThread
);
44 // Define a new application type
45 class MyApp
: public wxApp
48 virtual bool OnInit();
51 // all the threads currently alive - as soon as the thread terminates, it's
52 // removed from the array
53 wxArrayThread m_threads
;
55 // crit section protects access to all of the arrays below
56 wxCriticalSection m_critsect
;
59 // Create a new application object
62 // Define a new frame type
63 class MyFrame
: public wxFrame
67 MyFrame(wxFrame
*frame
, const wxString
& title
, int x
, int y
, int w
, int h
);
70 void WriteText(const wxString
& text
) { m_txtctrl
->WriteText(text
); }
72 // accessors for MyWorkerThread (called in its context!)
76 void OnQuit(wxCommandEvent
& event
);
77 void OnAbout(wxCommandEvent
& event
);
78 void OnClear(wxCommandEvent
& event
);
80 void OnStartThread(wxCommandEvent
& event
);
81 void OnStartThreads(wxCommandEvent
& event
);
82 void OnStopThread(wxCommandEvent
& event
);
83 void OnPauseThread(wxCommandEvent
& event
);
84 void OnResumeThread(wxCommandEvent
& event
);
86 void OnStartWorker(wxCommandEvent
& event
);
87 void OnWorkerEvent(wxCommandEvent
& event
);
88 void OnUpdateWorker(wxUpdateUIEvent
& event
);
90 void OnIdle(wxIdleEvent
&event
);
93 // helper function - creates a new thread (but doesn't run it)
94 MyThread
*CreateThread();
96 // just some place to put our messages in
97 wxTextCtrl
*m_txtctrl
;
99 // remember the number of running threads and total number of threads
100 size_t m_nRunning
, m_nCount
;
102 // the progress dialog which we show while worker thread is running
103 wxProgressDialog
*m_dlgProgress
;
105 // was the worker thread cancelled by user?
108 // protects m_cancelled
109 wxCriticalSection m_critsectWork
;
111 DECLARE_EVENT_TABLE()
114 // ID for the menu commands
121 TEST_START_THREAD
= 201,
127 WORKER_EVENT
// this one gets sent from the worker thread
130 //--------------------------------------------------
132 //--------------------------------------------------
134 class MyThread
: public wxThread
137 MyThread(MyFrame
*frame
);
139 // thread execution starts here
140 virtual void *Entry();
142 // called when the thread exits - whether it terminates normally or is
143 // stopped with Delete() (but not when it is Kill()ed!)
144 virtual void OnExit();
146 // write something to the text control
147 void WriteText(const wxString
& text
);
154 MyThread::MyThread(MyFrame
*frame
)
161 void MyThread::WriteText(const wxString
& text
)
165 // before doing any GUI calls we must ensure that this thread is the only
171 m_frame
->WriteText(msg
);
176 void MyThread::OnExit()
178 wxCriticalSectionLocker
locker(wxGetApp().m_critsect
);
180 wxGetApp().m_threads
.Remove(this);
183 void *MyThread::Entry()
187 text
.Printf("Thread 0x%x started (priority = %d).\n",
188 GetId(), GetPriority());
190 // wxLogMessage(text); -- test wxLog thread safeness
192 for ( m_count
= 0; m_count
< 10; m_count
++ )
194 // check if we were asked to exit
198 text
.Printf("[%u] Thread 0x%x here.\n", m_count
, GetId());
201 // wxSleep() can't be called from non-GUI thread!
202 wxThread::Sleep(1000);
205 text
.Printf("Thread 0x%x finished.\n", GetId());
207 // wxLogMessage(text); -- test wxLog thread safeness
212 //--------------------------------------------------
214 //--------------------------------------------------
216 class MyWorkerThread
: public wxThread
219 MyWorkerThread(MyFrame
*frame
);
221 // thread execution starts here
222 virtual void *Entry();
224 // called when the thread exits - whether it terminates normally or is
225 // stopped with Delete() (but not when it is Kill()ed!)
226 virtual void OnExit();
233 MyWorkerThread::MyWorkerThread(MyFrame
*frame
)
240 void MyWorkerThread::OnExit()
244 void *MyWorkerThread::Entry()
246 for ( m_count
= 0; !m_frame
->Cancelled() && (m_count
< 100); m_count
++ )
248 // check if we were asked to exit
253 text
.Printf("[%u] Thread 0x%x here!!", m_count
, GetId());
255 // create any type of command event here
256 wxCommandEvent
event( wxEVT_COMMAND_MENU_SELECTED
, WORKER_EVENT
);
257 event
.SetInt( m_count
);
258 event
.SetString( text
);
260 // send in a thread-safe way
261 wxPostEvent( m_frame
, event
);
264 // m_frame->AddPendingEvent( event );
266 // wxSleep() can't be called from non-main thread!
267 wxThread::Sleep(200);
270 wxCommandEvent
event( wxEVT_COMMAND_MENU_SELECTED
, WORKER_EVENT
);
271 event
.SetInt(-1); // that's all
272 wxPostEvent( m_frame
, event
);
277 //--------------------------------------------------
279 //--------------------------------------------------
281 BEGIN_EVENT_TABLE(MyFrame
, wxFrame
)
282 EVT_MENU(TEST_QUIT
, MyFrame::OnQuit
)
283 EVT_MENU(TEST_ABOUT
, MyFrame::OnAbout
)
284 EVT_MENU(TEST_CLEAR
, MyFrame::OnClear
)
285 EVT_MENU(TEST_START_THREAD
, MyFrame::OnStartThread
)
286 EVT_MENU(TEST_START_THREADS
, MyFrame::OnStartThreads
)
287 EVT_MENU(TEST_STOP_THREAD
, MyFrame::OnStopThread
)
288 EVT_MENU(TEST_PAUSE_THREAD
, MyFrame::OnPauseThread
)
289 EVT_MENU(TEST_RESUME_THREAD
, MyFrame::OnResumeThread
)
291 EVT_UPDATE_UI(TEST_START_WORKER
, MyFrame::OnUpdateWorker
)
292 EVT_MENU(TEST_START_WORKER
, MyFrame::OnStartWorker
)
293 EVT_MENU(WORKER_EVENT
, MyFrame::OnWorkerEvent
)
295 EVT_IDLE(MyFrame::OnIdle
)
298 // `Main program' equivalent, creating windows and returning main app frame
302 wxLog::AddTraceMask("thread");
305 // Create the main frame window
306 MyFrame
*frame
= new MyFrame((wxFrame
*)NULL
, "wxWindows threads sample",
310 wxMenu
*file_menu
= new wxMenu
;
312 file_menu
->Append(TEST_CLEAR
, "&Clear log\tCtrl-L");
313 file_menu
->AppendSeparator();
314 file_menu
->Append(TEST_ABOUT
, "&About");
315 file_menu
->AppendSeparator();
316 file_menu
->Append(TEST_QUIT
, "E&xit\tAlt-X");
317 wxMenuBar
*menu_bar
= new wxMenuBar
;
318 menu_bar
->Append(file_menu
, "&File");
320 wxMenu
*thread_menu
= new wxMenu
;
321 thread_menu
->Append(TEST_START_THREAD
, "&Start a new thread\tCtrl-N");
322 thread_menu
->Append(TEST_START_THREADS
, "Start &many threads at once");
323 thread_menu
->Append(TEST_STOP_THREAD
, "S&top a running thread\tCtrl-S");
324 thread_menu
->AppendSeparator();
325 thread_menu
->Append(TEST_PAUSE_THREAD
, "&Pause a running thread\tCtrl-P");
326 thread_menu
->Append(TEST_RESUME_THREAD
, "&Resume suspended thread\tCtrl-R");
327 thread_menu
->AppendSeparator();
328 thread_menu
->Append(TEST_START_WORKER
, "Start &worker thread\tCtrl-W");
330 menu_bar
->Append(thread_menu
, "&Thread");
331 frame
->SetMenuBar(menu_bar
);
341 // My frame constructor
342 MyFrame::MyFrame(wxFrame
*frame
, const wxString
& title
,
343 int x
, int y
, int w
, int h
)
344 : wxFrame(frame
, -1, title
, wxPoint(x
, y
), wxSize(w
, h
))
346 m_nRunning
= m_nCount
= 0;
348 m_dlgProgress
= (wxProgressDialog
*)NULL
;
352 m_txtctrl
= new wxTextCtrl(this, -1, "", wxPoint(0, 0), wxSize(0, 0),
353 wxTE_MULTILINE
| wxTE_READONLY
);
357 MyThread
*MyFrame::CreateThread()
359 MyThread
*thread
= new MyThread(this);
361 if ( thread
->Create() != wxTHREAD_NO_ERROR
)
363 wxLogError("Can't create thread!");
366 wxCriticalSectionLocker
enter(wxGetApp().m_critsect
);
367 wxGetApp().m_threads
.Add(thread
);
372 void MyFrame::OnStartThreads(wxCommandEvent
& WXUNUSED(event
) )
374 static long s_num
= 10;
376 s_num
= wxGetNumberFromUser("How many threads to start: ", "",
377 "wxThread sample", s_num
, 1, 10000, this);
385 size_t count
= (size_t)s_num
, n
;
387 wxArrayThread threads
;
389 // first create them all...
390 for ( n
= 0; n
< count
; n
++ )
392 wxThread
*thr
= CreateThread();
394 // we want to show the effect of SetPriority(): the first thread will
395 // have the lowest priority, the second - the highest, all the rest
398 thr
->SetPriority(WXTHREAD_MIN_PRIORITY
);
400 thr
->SetPriority(WXTHREAD_MAX_PRIORITY
);
402 thr
->SetPriority(WXTHREAD_DEFAULT_PRIORITY
);
408 msg
.Printf("%d new threads created.", count
);
409 SetStatusText(msg
, 1);
411 // ...and then start them
412 for ( n
= 0; n
< count
; n
++ )
418 void MyFrame::OnStartThread(wxCommandEvent
& WXUNUSED(event
) )
420 MyThread
*thread
= CreateThread();
422 if ( thread
->Run() != wxTHREAD_NO_ERROR
)
424 wxLogError("Can't start thread!");
427 SetStatusText("New thread started.", 1);
430 void MyFrame::OnStopThread(wxCommandEvent
& WXUNUSED(event
) )
432 wxGetApp().m_critsect
.Enter();
434 // stop the last thread
435 if ( wxGetApp().m_threads
.IsEmpty() )
437 wxLogError("No thread to stop!");
439 wxGetApp().m_critsect
.Leave();
443 wxThread
*thread
= wxGetApp().m_threads
.Last();
445 // it's important to leave critical section before calling Delete()
446 // because delete will (implicitly) call OnExit() which also tries
447 // to enter the same crit section - would dead lock.
448 wxGetApp().m_critsect
.Leave();
452 SetStatusText("Thread stopped.", 1);
456 void MyFrame::OnResumeThread(wxCommandEvent
& WXUNUSED(event
) )
458 wxCriticalSectionLocker
enter(wxGetApp().m_critsect
);
460 // resume first suspended thread
461 size_t n
= 0, count
= wxGetApp().m_threads
.Count();
462 while ( n
< count
&& !wxGetApp().m_threads
[n
]->IsPaused() )
467 wxLogError("No thread to resume!");
471 wxGetApp().m_threads
[n
]->Resume();
473 SetStatusText("Thread resumed.", 1);
477 void MyFrame::OnPauseThread(wxCommandEvent
& WXUNUSED(event
) )
479 wxCriticalSectionLocker
enter(wxGetApp().m_critsect
);
481 // pause last running thread
482 int n
= wxGetApp().m_threads
.Count() - 1;
483 while ( n
>= 0 && !wxGetApp().m_threads
[n
]->IsRunning() )
488 wxLogError("No thread to pause!");
492 wxGetApp().m_threads
[n
]->Pause();
494 SetStatusText("Thread paused.", 1);
498 // set the frame title indicating the current number of threads
499 void MyFrame::OnIdle(wxIdleEvent
&event
)
501 // update the counts of running/total threads
503 nCount
= wxGetApp().m_threads
.Count();
504 for ( size_t n
= 0; n
< nCount
; n
++ )
506 if ( wxGetApp().m_threads
[n
]->IsRunning() )
510 if ( nCount
!= m_nCount
|| nRunning
!= m_nRunning
)
512 m_nRunning
= nRunning
;
515 wxLogStatus(this, "%u threads total, %u running.", nCount
, nRunning
);
517 //else: avoid flicker - don't print anything
520 void MyFrame::OnQuit(wxCommandEvent
& WXUNUSED(event
) )
522 size_t count
= wxGetApp().m_threads
.Count();
523 for ( size_t i
= 0; i
< count
; i
++ )
525 wxGetApp().m_threads
[0]->Delete();
531 void MyFrame::OnAbout(wxCommandEvent
& WXUNUSED(event
) )
533 wxMessageDialog
dialog(this, "wxWindows multithreaded application sample\n"
534 "(c) 1998 Julian Smart, Guilhem Lavaux\n"
535 "(c) 1999 Vadim Zeitlin\n"
536 "(c) 2000 Robert Roebling",
537 "About wxThread sample",
538 wxOK
| wxICON_INFORMATION
);
543 void MyFrame::OnClear(wxCommandEvent
& WXUNUSED(event
))
547 wxLogTrace("-------- log window cleared --------");
553 void MyFrame::OnUpdateWorker(wxUpdateUIEvent
& event
)
555 event
.Enable( m_dlgProgress
== NULL
);
558 void MyFrame::OnStartWorker(wxCommandEvent
& WXUNUSED(event
))
560 MyWorkerThread
*thread
= new MyWorkerThread(this);
562 if ( thread
->Create() != wxTHREAD_NO_ERROR
)
564 wxLogError("Can't create thread!");
567 m_dlgProgress
= new wxProgressDialog
570 "Wait until the thread terminates or press [Cancel]",
576 wxPD_ESTIMATED_TIME
|
580 // thread is not running yet, no need for crit sect
586 void MyFrame::OnWorkerEvent(wxCommandEvent
& event
)
589 WriteText( "Got message from worker thread: " );
590 WriteText( event
.GetString() );
593 int n
= event
.GetInt();
596 m_dlgProgress
->Destroy();
597 m_dlgProgress
= (wxProgressDialog
*)NULL
;
599 // the dialog is aborted because the event came from another thread, so
600 // we may need to wake up the main event loop for the dialog to be
606 if ( !m_dlgProgress
->Update(n
) )
608 wxCriticalSectionLocker
lock(m_critsectWork
);
616 bool MyFrame::Cancelled()
618 wxCriticalSectionLocker
lock(m_critsectWork
);