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
18 #pragma implementation "thread.cpp"
19 #pragma interface "thread.cpp"
22 // For compilers that support precompilation, includes "wx/wx.h".
23 #include "wx/wxprec.h"
34 #error "This sample requires thread support!"
35 #endif // wxUSE_THREADS
37 #include "wx/thread.h"
38 #include "wx/dynarray.h"
41 #include "wx/progdlg.h"
43 // uncomment this to get some debugging messages from the trace code
47 WX_DEFINE_ARRAY(wxThread
*, wxArrayThread
);
49 // Define a new application type
50 class MyApp
: public wxApp
53 virtual bool OnInit();
56 // all the threads currently alive - as soon as the thread terminates, it's
57 // removed from the array
58 wxArrayThread m_threads
;
60 // crit section protects access to all of the arrays below
61 wxCriticalSection m_critsect
;
64 // Create a new application object
67 // Define a new frame type
68 class MyFrame
: public wxFrame
72 MyFrame(wxFrame
*frame
, const wxString
& title
, int x
, int y
, int w
, int h
);
75 void WriteText(const wxString
& text
) { m_txtctrl
->WriteText(text
); }
77 // accessors for MyWorkerThread (called in its context!)
81 void OnQuit(wxCommandEvent
& event
);
82 void OnAbout(wxCommandEvent
& event
);
83 void OnClear(wxCommandEvent
& event
);
85 void OnStartThread(wxCommandEvent
& event
);
86 void OnStartThreads(wxCommandEvent
& event
);
87 void OnStopThread(wxCommandEvent
& event
);
88 void OnPauseThread(wxCommandEvent
& event
);
89 void OnResumeThread(wxCommandEvent
& event
);
91 void OnStartWorker(wxCommandEvent
& event
);
92 void OnWorkerEvent(wxCommandEvent
& event
);
93 void OnUpdateWorker(wxUpdateUIEvent
& event
);
95 void OnIdle(wxIdleEvent
&event
);
98 // helper function - creates a new thread (but doesn't run it)
99 MyThread
*CreateThread();
101 // just some place to put our messages in
102 wxTextCtrl
*m_txtctrl
;
104 // remember the number of running threads and total number of threads
105 size_t m_nRunning
, m_nCount
;
107 // the progress dialog which we show while worker thread is running
108 wxProgressDialog
*m_dlgProgress
;
110 // was the worker thread cancelled by user?
113 // protects m_cancelled
114 wxCriticalSection m_critsectWork
;
116 DECLARE_EVENT_TABLE()
119 // ID for the menu commands
126 TEST_START_THREAD
= 201,
132 WORKER_EVENT
// this one gets sent from the worker thread
135 //--------------------------------------------------
137 //--------------------------------------------------
139 class MyThread
: public wxThread
142 MyThread(MyFrame
*frame
);
144 // thread execution starts here
145 virtual void *Entry();
147 // called when the thread exits - whether it terminates normally or is
148 // stopped with Delete() (but not when it is Kill()ed!)
149 virtual void OnExit();
151 // write something to the text control
152 void WriteText(const wxString
& text
);
159 MyThread::MyThread(MyFrame
*frame
)
166 void MyThread::WriteText(const wxString
& text
)
170 // before doing any GUI calls we must ensure that this thread is the only
176 m_frame
->WriteText(msg
);
181 void MyThread::OnExit()
183 wxCriticalSectionLocker
locker(wxGetApp().m_critsect
);
185 wxGetApp().m_threads
.Remove(this);
188 void *MyThread::Entry()
192 text
.Printf("Thread 0x%x started (priority = %d).\n",
193 GetId(), GetPriority());
195 // wxLogMessage(text); -- test wxLog thread safeness
197 for ( m_count
= 0; m_count
< 10; m_count
++ )
199 // check if we were asked to exit
203 text
.Printf("[%u] Thread 0x%x here.\n", m_count
, GetId());
206 // wxSleep() can't be called from non-GUI thread!
207 wxThread::Sleep(1000);
210 text
.Printf("Thread 0x%x finished.\n", GetId());
212 // wxLogMessage(text); -- test wxLog thread safeness
217 //--------------------------------------------------
219 //--------------------------------------------------
221 class MyWorkerThread
: public wxThread
224 MyWorkerThread(MyFrame
*frame
);
226 // thread execution starts here
227 virtual void *Entry();
229 // called when the thread exits - whether it terminates normally or is
230 // stopped with Delete() (but not when it is Kill()ed!)
231 virtual void OnExit();
238 MyWorkerThread::MyWorkerThread(MyFrame
*frame
)
245 void MyWorkerThread::OnExit()
249 void *MyWorkerThread::Entry()
251 for ( m_count
= 0; !m_frame
->Cancelled() && (m_count
< 100); m_count
++ )
253 // check if we were asked to exit
258 text
.Printf("[%u] Thread 0x%x here!!", m_count
, GetId());
260 // create any type of command event here
261 wxCommandEvent
event( wxEVT_COMMAND_MENU_SELECTED
, WORKER_EVENT
);
262 event
.SetInt( m_count
);
263 event
.SetString( text
);
265 // send in a thread-safe way
266 wxPostEvent( m_frame
, event
);
269 // m_frame->AddPendingEvent( event );
271 // wxSleep() can't be called from non-main thread!
272 wxThread::Sleep(200);
275 wxCommandEvent
event( wxEVT_COMMAND_MENU_SELECTED
, WORKER_EVENT
);
276 event
.SetInt(-1); // that's all
277 wxPostEvent( m_frame
, event
);
282 //--------------------------------------------------
284 //--------------------------------------------------
286 BEGIN_EVENT_TABLE(MyFrame
, wxFrame
)
287 EVT_MENU(TEST_QUIT
, MyFrame::OnQuit
)
288 EVT_MENU(TEST_ABOUT
, MyFrame::OnAbout
)
289 EVT_MENU(TEST_CLEAR
, MyFrame::OnClear
)
290 EVT_MENU(TEST_START_THREAD
, MyFrame::OnStartThread
)
291 EVT_MENU(TEST_START_THREADS
, MyFrame::OnStartThreads
)
292 EVT_MENU(TEST_STOP_THREAD
, MyFrame::OnStopThread
)
293 EVT_MENU(TEST_PAUSE_THREAD
, MyFrame::OnPauseThread
)
294 EVT_MENU(TEST_RESUME_THREAD
, MyFrame::OnResumeThread
)
296 EVT_UPDATE_UI(TEST_START_WORKER
, MyFrame::OnUpdateWorker
)
297 EVT_MENU(TEST_START_WORKER
, MyFrame::OnStartWorker
)
298 EVT_MENU(WORKER_EVENT
, MyFrame::OnWorkerEvent
)
300 EVT_IDLE(MyFrame::OnIdle
)
303 // `Main program' equivalent, creating windows and returning main app frame
307 wxLog::AddTraceMask("thread");
310 // Create the main frame window
311 MyFrame
*frame
= new MyFrame((wxFrame
*)NULL
, "wxWindows threads sample",
315 wxMenu
*file_menu
= new wxMenu
;
317 file_menu
->Append(TEST_CLEAR
, "&Clear log\tCtrl-L");
318 file_menu
->AppendSeparator();
319 file_menu
->Append(TEST_ABOUT
, "&About");
320 file_menu
->AppendSeparator();
321 file_menu
->Append(TEST_QUIT
, "E&xit\tAlt-X");
322 wxMenuBar
*menu_bar
= new wxMenuBar
;
323 menu_bar
->Append(file_menu
, "&File");
325 wxMenu
*thread_menu
= new wxMenu
;
326 thread_menu
->Append(TEST_START_THREAD
, "&Start a new thread\tCtrl-N");
327 thread_menu
->Append(TEST_START_THREADS
, "Start &many threads at once");
328 thread_menu
->Append(TEST_STOP_THREAD
, "S&top a running thread\tCtrl-S");
329 thread_menu
->AppendSeparator();
330 thread_menu
->Append(TEST_PAUSE_THREAD
, "&Pause a running thread\tCtrl-P");
331 thread_menu
->Append(TEST_RESUME_THREAD
, "&Resume suspended thread\tCtrl-R");
332 thread_menu
->AppendSeparator();
333 thread_menu
->Append(TEST_START_WORKER
, "Start &worker thread\tCtrl-W");
335 menu_bar
->Append(thread_menu
, "&Thread");
336 frame
->SetMenuBar(menu_bar
);
346 // My frame constructor
347 MyFrame::MyFrame(wxFrame
*frame
, const wxString
& title
,
348 int x
, int y
, int w
, int h
)
349 : wxFrame(frame
, -1, title
, wxPoint(x
, y
), wxSize(w
, h
))
351 m_nRunning
= m_nCount
= 0;
353 m_dlgProgress
= (wxProgressDialog
*)NULL
;
357 m_txtctrl
= new wxTextCtrl(this, -1, "", wxPoint(0, 0), wxSize(0, 0),
358 wxTE_MULTILINE
| wxTE_READONLY
);
362 MyThread
*MyFrame::CreateThread()
364 MyThread
*thread
= new MyThread(this);
366 if ( thread
->Create() != wxTHREAD_NO_ERROR
)
368 wxLogError("Can't create thread!");
371 wxCriticalSectionLocker
enter(wxGetApp().m_critsect
);
372 wxGetApp().m_threads
.Add(thread
);
377 void MyFrame::OnStartThreads(wxCommandEvent
& WXUNUSED(event
) )
379 static long s_num
= 10;
381 s_num
= wxGetNumberFromUser("How many threads to start: ", "",
382 "wxThread sample", s_num
, 1, 10000, this);
390 size_t count
= (size_t)s_num
, n
;
392 wxArrayThread threads
;
394 // first create them all...
395 for ( n
= 0; n
< count
; n
++ )
397 wxThread
*thr
= CreateThread();
399 // we want to show the effect of SetPriority(): the first thread will
400 // have the lowest priority, the second - the highest, all the rest
403 thr
->SetPriority(WXTHREAD_MIN_PRIORITY
);
405 thr
->SetPriority(WXTHREAD_MAX_PRIORITY
);
407 thr
->SetPriority(WXTHREAD_DEFAULT_PRIORITY
);
413 msg
.Printf("%d new threads created.", count
);
414 SetStatusText(msg
, 1);
416 // ...and then start them
417 for ( n
= 0; n
< count
; n
++ )
423 void MyFrame::OnStartThread(wxCommandEvent
& WXUNUSED(event
) )
425 MyThread
*thread
= CreateThread();
427 if ( thread
->Run() != wxTHREAD_NO_ERROR
)
429 wxLogError("Can't start thread!");
432 SetStatusText("New thread started.", 1);
435 void MyFrame::OnStopThread(wxCommandEvent
& WXUNUSED(event
) )
437 wxGetApp().m_critsect
.Enter();
439 // stop the last thread
440 if ( wxGetApp().m_threads
.IsEmpty() )
442 wxLogError("No thread to stop!");
444 wxGetApp().m_critsect
.Leave();
448 wxThread
*thread
= wxGetApp().m_threads
.Last();
450 // it's important to leave critical section before calling Delete()
451 // because delete will (implicitly) call OnExit() which also tries
452 // to enter the same crit section - would dead lock.
453 wxGetApp().m_critsect
.Leave();
457 SetStatusText("Thread stopped.", 1);
461 void MyFrame::OnResumeThread(wxCommandEvent
& WXUNUSED(event
) )
463 wxCriticalSectionLocker
enter(wxGetApp().m_critsect
);
465 // resume first suspended thread
466 size_t n
= 0, count
= wxGetApp().m_threads
.Count();
467 while ( n
< count
&& !wxGetApp().m_threads
[n
]->IsPaused() )
472 wxLogError("No thread to resume!");
476 wxGetApp().m_threads
[n
]->Resume();
478 SetStatusText("Thread resumed.", 1);
482 void MyFrame::OnPauseThread(wxCommandEvent
& WXUNUSED(event
) )
484 wxCriticalSectionLocker
enter(wxGetApp().m_critsect
);
486 // pause last running thread
487 int n
= wxGetApp().m_threads
.Count() - 1;
488 while ( n
>= 0 && !wxGetApp().m_threads
[n
]->IsRunning() )
493 wxLogError("No thread to pause!");
497 wxGetApp().m_threads
[n
]->Pause();
499 SetStatusText("Thread paused.", 1);
503 // set the frame title indicating the current number of threads
504 void MyFrame::OnIdle(wxIdleEvent
&event
)
506 // update the counts of running/total threads
508 nCount
= wxGetApp().m_threads
.Count();
509 for ( size_t n
= 0; n
< nCount
; n
++ )
511 if ( wxGetApp().m_threads
[n
]->IsRunning() )
515 if ( nCount
!= m_nCount
|| nRunning
!= m_nRunning
)
517 m_nRunning
= nRunning
;
520 wxLogStatus(this, "%u threads total, %u running.", nCount
, nRunning
);
522 //else: avoid flicker - don't print anything
525 void MyFrame::OnQuit(wxCommandEvent
& WXUNUSED(event
) )
527 size_t count
= wxGetApp().m_threads
.Count();
528 for ( size_t i
= 0; i
< count
; i
++ )
530 wxGetApp().m_threads
[0]->Delete();
536 void MyFrame::OnAbout(wxCommandEvent
& WXUNUSED(event
) )
538 wxMessageDialog
dialog(this, "wxWindows multithreaded application sample\n"
539 "(c) 1998 Julian Smart, Guilhem Lavaux\n"
540 "(c) 1999 Vadim Zeitlin\n"
541 "(c) 2000 Robert Roebling",
542 "About wxThread sample",
543 wxOK
| wxICON_INFORMATION
);
548 void MyFrame::OnClear(wxCommandEvent
& WXUNUSED(event
))
552 wxLogTrace("-------- log window cleared --------");
558 void MyFrame::OnUpdateWorker(wxUpdateUIEvent
& event
)
560 event
.Enable( m_dlgProgress
== NULL
);
563 void MyFrame::OnStartWorker(wxCommandEvent
& WXUNUSED(event
))
565 MyWorkerThread
*thread
= new MyWorkerThread(this);
567 if ( thread
->Create() != wxTHREAD_NO_ERROR
)
569 wxLogError("Can't create thread!");
572 m_dlgProgress
= new wxProgressDialog
575 "Wait until the thread terminates or press [Cancel]",
581 wxPD_ESTIMATED_TIME
|
585 // thread is not running yet, no need for crit sect
591 void MyFrame::OnWorkerEvent(wxCommandEvent
& event
)
594 WriteText( "Got message from worker thread: " );
595 WriteText( event
.GetString() );
598 int n
= event
.GetInt();
601 m_dlgProgress
->Destroy();
602 m_dlgProgress
= (wxProgressDialog
*)NULL
;
604 // the dialog is aborted because the event came from another thread, so
605 // we may need to wake up the main event loop for the dialog to be
611 if ( !m_dlgProgress
->Update(n
) )
613 wxCriticalSectionLocker
lock(m_critsectWork
);
621 bool MyFrame::Cancelled()
623 wxCriticalSectionLocker
lock(m_critsectWork
);