]> git.saurik.com Git - wxWidgets.git/blob - samples/thread/thread.cpp
Changes to make commandline compilation with VC6 match the same settings and LIB...
[wxWidgets.git] / samples / thread / thread.cpp
1 /////////////////////////////////////////////////////////////////////////////
2 // Name: thread.cpp
3 // Purpose: wxWindows thread sample
4 // Author: Julian Smart(minimal)/Guilhem Lavaux(thread test)
5 // Modified by:
6 // Created: 06/16/98
7 // RCS-ID: $Id$
8 // Copyright: (c) Julian Smart, Markus Holzem, Guilhem Lavaux
9 // Licence: wxWindows license
10 /////////////////////////////////////////////////////////////////////////////
11
12 /*
13 TODO: use worker threads to update progress controls instead of writing
14 messages - it will be more visual
15 */
16
17 // For compilers that support precompilation, includes "wx/wx.h".
18 #include "wx/wxprec.h"
19
20 #ifdef __BORLANDC__
21 #pragma hdrstop
22 #endif
23
24 #ifndef WX_PRECOMP
25 #include "wx/wx.h"
26 #endif
27
28 #if !wxUSE_THREADS
29 #error "This sample requires thread support!"
30 #endif // wxUSE_THREADS
31
32 #include "wx/thread.h"
33 #include "wx/dynarray.h"
34 #include "wx/time.h"
35
36 #include "wx/progdlg.h"
37
38 // uncomment this to get some debugging messages from the trace code
39 //#define TRACE
40
41 class MyThread;
42 WX_DEFINE_ARRAY(wxThread *, wxArrayThread);
43
44 // Define a new application type
45 class MyApp : public wxApp
46 {
47 public:
48 virtual bool OnInit();
49
50 public:
51 // all the threads currently alive - as soon as the thread terminates, it's
52 // removed from the array
53 wxArrayThread m_threads;
54
55 // crit section protects access to all of the arrays below
56 wxCriticalSection m_critsect;
57 };
58
59 // Create a new application object
60 IMPLEMENT_APP(MyApp)
61
62 // Define a new frame type
63 class MyFrame: public wxFrame
64 {
65 public:
66 // ctor
67 MyFrame(wxFrame *frame, const wxString& title, int x, int y, int w, int h);
68
69 // operations
70 void WriteText(const wxString& text) { m_txtctrl->WriteText(text); }
71
72 // accessors for MyWorkerThread (called in its context!)
73 bool Cancelled();
74
75 // callbacks
76 void OnQuit(wxCommandEvent& event);
77 void OnAbout(wxCommandEvent& event);
78 void OnClear(wxCommandEvent& event);
79
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);
85
86 void OnStartWorker(wxCommandEvent& event);
87 void OnWorkerEvent(wxCommandEvent& event);
88 void OnUpdateWorker(wxUpdateUIEvent& event);
89
90 void OnIdle(wxIdleEvent &event);
91
92 private:
93 // helper function - creates a new thread (but doesn't run it)
94 MyThread *CreateThread();
95
96 // just some place to put our messages in
97 wxTextCtrl *m_txtctrl;
98
99 // remember the number of running threads and total number of threads
100 size_t m_nRunning, m_nCount;
101
102 // the progress dialog which we show while worker thread is running
103 wxProgressDialog *m_dlgProgress;
104
105 // was the worker thread cancelled by user?
106 bool m_cancelled;
107
108 // protects m_cancelled
109 wxCriticalSection m_critsectWork;
110
111 DECLARE_EVENT_TABLE()
112 };
113
114 // ID for the menu commands
115 enum
116 {
117 TEST_QUIT = 1,
118 TEST_TEXT = 101,
119 TEST_ABOUT,
120 TEST_CLEAR,
121 TEST_START_THREAD = 201,
122 TEST_START_THREADS,
123 TEST_STOP_THREAD,
124 TEST_PAUSE_THREAD,
125 TEST_RESUME_THREAD,
126 TEST_START_WORKER,
127 WORKER_EVENT // this one gets sent from the worker thread
128 };
129
130 //--------------------------------------------------
131 // GUI thread
132 //--------------------------------------------------
133
134 class MyThread : public wxThread
135 {
136 public:
137 MyThread(MyFrame *frame);
138
139 // thread execution starts here
140 virtual void *Entry();
141
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();
145
146 // write something to the text control
147 void WriteText(const wxString& text);
148
149 public:
150 size_t m_count;
151 MyFrame *m_frame;
152 };
153
154 MyThread::MyThread(MyFrame *frame)
155 : wxThread()
156 {
157 m_count = 0;
158 m_frame = frame;
159 }
160
161 void MyThread::WriteText(const wxString& text)
162 {
163 wxString msg;
164
165 // before doing any GUI calls we must ensure that this thread is the only
166 // one doing it!
167
168 wxMutexGuiEnter();
169
170 msg << text;
171 m_frame->WriteText(msg);
172
173 wxMutexGuiLeave();
174 }
175
176 void MyThread::OnExit()
177 {
178 wxCriticalSectionLocker locker(wxGetApp().m_critsect);
179
180 wxGetApp().m_threads.Remove(this);
181 }
182
183 void *MyThread::Entry()
184 {
185 wxString text;
186
187 text.Printf(wxT("Thread 0x%x started (priority = %d).\n"),
188 GetId(), GetPriority());
189 WriteText(text);
190 // wxLogMessage(text); -- test wxLog thread safeness
191
192 for ( m_count = 0; m_count < 10; m_count++ )
193 {
194 // check if we were asked to exit
195 if ( TestDestroy() )
196 break;
197
198 text.Printf(wxT("[%u] Thread 0x%x here.\n"), m_count, GetId());
199 WriteText(text);
200
201 // wxSleep() can't be called from non-GUI thread!
202 wxThread::Sleep(1000);
203 }
204
205 text.Printf(wxT("Thread 0x%x finished.\n"), GetId());
206 WriteText(text);
207 // wxLogMessage(text); -- test wxLog thread safeness
208
209 return NULL;
210 }
211
212 //--------------------------------------------------
213 // worker thread
214 //--------------------------------------------------
215
216 class MyWorkerThread : public wxThread
217 {
218 public:
219 MyWorkerThread(MyFrame *frame);
220
221 // thread execution starts here
222 virtual void *Entry();
223
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();
227
228 public:
229 MyFrame *m_frame;
230 size_t m_count;
231 };
232
233 MyWorkerThread::MyWorkerThread(MyFrame *frame)
234 : wxThread()
235 {
236 m_frame = frame;
237 m_count = 0;
238 }
239
240 void MyWorkerThread::OnExit()
241 {
242 }
243
244 void *MyWorkerThread::Entry()
245 {
246 for ( m_count = 0; !m_frame->Cancelled() && (m_count < 100); m_count++ )
247 {
248 // check if we were asked to exit
249 if ( TestDestroy() )
250 break;
251
252 wxString text;
253 text.Printf(wxT("[%u] Thread 0x%x here!!"), m_count, GetId());
254
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 );
259
260 // send in a thread-safe way
261 wxPostEvent( m_frame, event );
262
263 // same as:
264 // m_frame->AddPendingEvent( event );
265
266 // wxSleep() can't be called from non-main thread!
267 wxThread::Sleep(200);
268 }
269
270 wxCommandEvent event( wxEVT_COMMAND_MENU_SELECTED, WORKER_EVENT );
271 event.SetInt(-1); // that's all
272 wxPostEvent( m_frame, event );
273
274 return NULL;
275 }
276
277 //--------------------------------------------------
278 // main program
279 //--------------------------------------------------
280
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)
290
291 EVT_UPDATE_UI(TEST_START_WORKER, MyFrame::OnUpdateWorker)
292 EVT_MENU(TEST_START_WORKER, MyFrame::OnStartWorker)
293 EVT_MENU(WORKER_EVENT, MyFrame::OnWorkerEvent)
294
295 EVT_IDLE(MyFrame::OnIdle)
296 END_EVENT_TABLE()
297
298 // `Main program' equivalent, creating windows and returning main app frame
299 bool MyApp::OnInit()
300 {
301 #ifdef TRACE
302 wxLog::AddTraceMask("thread");
303 #endif
304
305 // Create the main frame window
306 MyFrame *frame = new MyFrame((wxFrame *)NULL, "wxWindows threads sample",
307 50, 50, 450, 340);
308
309 // Make a menubar
310 wxMenu *file_menu = new wxMenu;
311
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");
319
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");
329
330 menu_bar->Append(thread_menu, "&Thread");
331 frame->SetMenuBar(menu_bar);
332
333 // Show the frame
334 frame->Show(TRUE);
335
336 SetTopWindow(frame);
337
338 return TRUE;
339 }
340
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))
345 {
346 m_nRunning = m_nCount = 0;
347
348 m_dlgProgress = (wxProgressDialog *)NULL;
349
350 CreateStatusBar(2);
351
352 m_txtctrl = new wxTextCtrl(this, -1, "", wxPoint(0, 0), wxSize(0, 0),
353 wxTE_MULTILINE | wxTE_READONLY);
354
355 }
356
357 MyThread *MyFrame::CreateThread()
358 {
359 MyThread *thread = new MyThread(this);
360
361 if ( thread->Create() != wxTHREAD_NO_ERROR )
362 {
363 wxLogError(wxT("Can't create thread!"));
364 }
365
366 wxCriticalSectionLocker enter(wxGetApp().m_critsect);
367 wxGetApp().m_threads.Add(thread);
368
369 return thread;
370 }
371
372 void MyFrame::OnStartThreads(wxCommandEvent& WXUNUSED(event) )
373 {
374 static long s_num = 10;
375
376 s_num = wxGetNumberFromUser("How many threads to start: ", "",
377 "wxThread sample", s_num, 1, 10000, this);
378 if ( s_num == -1 )
379 {
380 s_num = 10;
381
382 return;
383 }
384
385 size_t count = (size_t)s_num, n;
386
387 wxArrayThread threads;
388
389 // first create them all...
390 for ( n = 0; n < count; n++ )
391 {
392 wxThread *thr = CreateThread();
393
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
396 // the normal one
397 if ( n == 0 )
398 thr->SetPriority(WXTHREAD_MIN_PRIORITY);
399 else if ( n == 1 )
400 thr->SetPriority(WXTHREAD_MAX_PRIORITY);
401 else
402 thr->SetPriority(WXTHREAD_DEFAULT_PRIORITY);
403
404 threads.Add(thr);
405 }
406
407 wxString msg;
408 msg.Printf(wxT("%d new threads created."), count);
409 SetStatusText(msg, 1);
410
411 // ...and then start them
412 for ( n = 0; n < count; n++ )
413 {
414 threads[n]->Run();
415 }
416 }
417
418 void MyFrame::OnStartThread(wxCommandEvent& WXUNUSED(event) )
419 {
420 MyThread *thread = CreateThread();
421
422 if ( thread->Run() != wxTHREAD_NO_ERROR )
423 {
424 wxLogError(wxT("Can't start thread!"));
425 }
426
427 SetStatusText("New thread started.", 1);
428 }
429
430 void MyFrame::OnStopThread(wxCommandEvent& WXUNUSED(event) )
431 {
432 wxGetApp().m_critsect.Enter();
433
434 // stop the last thread
435 if ( wxGetApp().m_threads.IsEmpty() )
436 {
437 wxLogError(wxT("No thread to stop!"));
438
439 wxGetApp().m_critsect.Leave();
440 }
441 else
442 {
443 wxThread *thread = wxGetApp().m_threads.Last();
444
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();
449
450 thread->Delete();
451
452 SetStatusText("Thread stopped.", 1);
453 }
454 }
455
456 void MyFrame::OnResumeThread(wxCommandEvent& WXUNUSED(event) )
457 {
458 wxCriticalSectionLocker enter(wxGetApp().m_critsect);
459
460 // resume first suspended thread
461 size_t n = 0, count = wxGetApp().m_threads.Count();
462 while ( n < count && !wxGetApp().m_threads[n]->IsPaused() )
463 n++;
464
465 if ( n == count )
466 {
467 wxLogError(wxT("No thread to resume!"));
468 }
469 else
470 {
471 wxGetApp().m_threads[n]->Resume();
472
473 SetStatusText("Thread resumed.", 1);
474 }
475 }
476
477 void MyFrame::OnPauseThread(wxCommandEvent& WXUNUSED(event) )
478 {
479 wxCriticalSectionLocker enter(wxGetApp().m_critsect);
480
481 // pause last running thread
482 int n = wxGetApp().m_threads.Count() - 1;
483 while ( n >= 0 && !wxGetApp().m_threads[n]->IsRunning() )
484 n--;
485
486 if ( n < 0 )
487 {
488 wxLogError(wxT("No thread to pause!"));
489 }
490 else
491 {
492 wxGetApp().m_threads[n]->Pause();
493
494 SetStatusText("Thread paused.", 1);
495 }
496 }
497
498 // set the frame title indicating the current number of threads
499 void MyFrame::OnIdle(wxIdleEvent &event)
500 {
501 // update the counts of running/total threads
502 size_t nRunning = 0,
503 nCount = wxGetApp().m_threads.Count();
504 for ( size_t n = 0; n < nCount; n++ )
505 {
506 if ( wxGetApp().m_threads[n]->IsRunning() )
507 nRunning++;
508 }
509
510 if ( nCount != m_nCount || nRunning != m_nRunning )
511 {
512 m_nRunning = nRunning;
513 m_nCount = nCount;
514
515 wxLogStatus(this, wxT("%u threads total, %u running."), nCount, nRunning);
516 }
517 //else: avoid flicker - don't print anything
518 }
519
520 void MyFrame::OnQuit(wxCommandEvent& WXUNUSED(event) )
521 {
522 size_t count = wxGetApp().m_threads.Count();
523 for ( size_t i = 0; i < count; i++ )
524 {
525 wxGetApp().m_threads[0]->Delete();
526 }
527
528 Close(TRUE);
529 }
530
531 void MyFrame::OnAbout(wxCommandEvent& WXUNUSED(event) )
532 {
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);
539
540 dialog.ShowModal();
541 }
542
543 void MyFrame::OnClear(wxCommandEvent& WXUNUSED(event))
544 {
545 #ifdef TRACE
546 // log a separator
547 wxLogTrace("-------- log window cleared --------");
548 #endif
549
550 m_txtctrl->Clear();
551 }
552
553 void MyFrame::OnUpdateWorker(wxUpdateUIEvent& event)
554 {
555 event.Enable( m_dlgProgress == NULL );
556 }
557
558 void MyFrame::OnStartWorker(wxCommandEvent& WXUNUSED(event))
559 {
560 MyWorkerThread *thread = new MyWorkerThread(this);
561
562 if ( thread->Create() != wxTHREAD_NO_ERROR )
563 {
564 wxLogError(wxT("Can't create thread!"));
565 }
566
567 m_dlgProgress = new wxProgressDialog
568 (
569 "Progress dialog",
570 "Wait until the thread terminates or press [Cancel]",
571 100,
572 this,
573 wxPD_CAN_ABORT |
574 wxPD_APP_MODAL |
575 wxPD_ELAPSED_TIME |
576 wxPD_ESTIMATED_TIME |
577 wxPD_REMAINING_TIME
578 );
579
580 // thread is not running yet, no need for crit sect
581 m_cancelled = FALSE;
582
583 thread->Run();
584 }
585
586 void MyFrame::OnWorkerEvent(wxCommandEvent& event)
587 {
588 #if 0
589 WriteText( "Got message from worker thread: " );
590 WriteText( event.GetString() );
591 WriteText( "\n" );
592 #else
593 int n = event.GetInt();
594 if ( n == -1 )
595 {
596 m_dlgProgress->Destroy();
597 m_dlgProgress = (wxProgressDialog *)NULL;
598
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
601 // really closed
602 wxWakeUpIdle();
603 }
604 else
605 {
606 if ( !m_dlgProgress->Update(n) )
607 {
608 wxCriticalSectionLocker lock(m_critsectWork);
609
610 m_cancelled = TRUE;
611 }
612 }
613 #endif
614 }
615
616 bool MyFrame::Cancelled()
617 {
618 wxCriticalSectionLocker lock(m_critsectWork);
619
620 return m_cancelled;
621 }