]> git.saurik.com Git - wxWidgets.git/blob - samples/thread/thread.cpp
61006e25a4ef21ba654a49fd12ff49210ea37a66
[wxWidgets.git] / samples / thread / thread.cpp
1 /////////////////////////////////////////////////////////////////////////////
2 // Name: thread.cpp
3 // Purpose: wxWindows thread sample
4 // Author: Guilhem Lavaux, Vadim Zeitlin
5 // Modified by:
6 // Created: 06/16/98
7 // RCS-ID: $Id$
8 // Copyright: (c) 1998-2002 wxWindows team
9 // Licence: wxWindows license
10 /////////////////////////////////////////////////////////////////////////////
11
12 // For compilers that support precompilation, includes "wx/wx.h".
13 #include "wx/wxprec.h"
14
15 #ifdef __BORLANDC__
16 #pragma hdrstop
17 #endif
18
19 #ifndef WX_PRECOMP
20 #include "wx/wx.h"
21 #endif
22
23 #if !wxUSE_THREADS
24 #error "This sample requires thread support!"
25 #endif // wxUSE_THREADS
26
27 #include "wx/thread.h"
28 #include "wx/dynarray.h"
29 #include "wx/numdlg.h"
30
31 #include "wx/progdlg.h"
32
33 // define this to use wxExecute in the exec tests, otherwise just use system
34 #define USE_EXECUTE
35
36 #ifdef USE_EXECUTE
37 #define EXEC(cmd) wxExecute((cmd), wxEXEC_SYNC)
38 #else
39 #define EXEC(cmd) system(cmd)
40 #endif
41
42 class MyThread;
43 WX_DEFINE_ARRAY_PTR(wxThread *, wxArrayThread);
44
45 // Define a new application type
46 class MyApp : public wxApp
47 {
48 public:
49 MyApp();
50 virtual ~MyApp();
51
52 virtual bool OnInit();
53
54 public:
55 // all the threads currently alive - as soon as the thread terminates, it's
56 // removed from the array
57 wxArrayThread m_threads;
58
59 // crit section protects access to all of the arrays below
60 wxCriticalSection m_critsect;
61
62 // semaphore used to wait for the threads to exit, see MyFrame::OnQuit()
63 wxSemaphore m_semAllDone;
64
65 // the last exiting thread should post to m_semAllDone if this is true
66 // (protected by the same m_critsect)
67 bool m_waitingUntilAllDone;
68 };
69
70 // Create a new application object
71 IMPLEMENT_APP(MyApp)
72
73 // Define a new frame type
74 class MyFrame: public wxFrame
75 {
76 public:
77 // ctor
78 MyFrame(wxFrame *frame, const wxString& title, int x, int y, int w, int h);
79 virtual ~MyFrame();
80
81 // operations
82 void WriteText(const wxString& text) { m_txtctrl->WriteText(text); }
83
84 // accessors for MyWorkerThread (called in its context!)
85 bool Cancelled();
86
87 protected:
88 // callbacks
89 void OnQuit(wxCommandEvent& event);
90 void OnClear(wxCommandEvent& event);
91
92 void OnStartThread(wxCommandEvent& event);
93 void OnStartThreads(wxCommandEvent& event);
94 void OnStopThread(wxCommandEvent& event);
95 void OnPauseThread(wxCommandEvent& event);
96 void OnResumeThread(wxCommandEvent& event);
97
98 void OnStartWorker(wxCommandEvent& event);
99 void OnWorkerEvent(wxCommandEvent& event);
100 void OnUpdateWorker(wxUpdateUIEvent& event);
101
102 void OnExecMain(wxCommandEvent& event);
103 void OnExecThread(wxCommandEvent& event);
104
105 void OnShowCPUs(wxCommandEvent& event);
106 void OnAbout(wxCommandEvent& event);
107
108 void OnIdle(wxIdleEvent &event);
109
110 private:
111 // helper function - creates a new thread (but doesn't run it)
112 MyThread *CreateThread();
113
114 // just some place to put our messages in
115 wxTextCtrl *m_txtctrl;
116
117 // remember the number of running threads and total number of threads
118 size_t m_nRunning, m_nCount;
119
120 // the progress dialog which we show while worker thread is running
121 wxProgressDialog *m_dlgProgress;
122
123 // was the worker thread cancelled by user?
124 bool m_cancelled;
125
126 // protects m_cancelled
127 wxCriticalSection m_critsectWork;
128
129 DECLARE_EVENT_TABLE()
130 };
131
132 // ID for the menu commands
133 enum
134 {
135 THREAD_QUIT = 1,
136 THREAD_TEXT = 101,
137 THREAD_CLEAR,
138 THREAD_START_THREAD = 201,
139 THREAD_START_THREADS,
140 THREAD_STOP_THREAD,
141 THREAD_PAUSE_THREAD,
142 THREAD_RESUME_THREAD,
143 THREAD_START_WORKER,
144
145 THREAD_EXEC_MAIN,
146 THREAD_EXEC_THREAD,
147
148 THREAD_SHOWCPUS,
149 THREAD_ABOUT,
150
151 WORKER_EVENT // this one gets sent from the worker thread
152 };
153
154 // ----------------------------------------------------------------------------
155 // GUI thread
156 // ----------------------------------------------------------------------------
157
158 class MyThread : public wxThread
159 {
160 public:
161 MyThread(MyFrame *frame);
162
163 // thread execution starts here
164 virtual void *Entry();
165
166 // called when the thread exits - whether it terminates normally or is
167 // stopped with Delete() (but not when it is Kill()ed!)
168 virtual void OnExit();
169
170 // write something to the text control
171 void WriteText(const wxString& text);
172
173 public:
174 size_t m_count;
175 MyFrame *m_frame;
176 };
177
178 MyThread::MyThread(MyFrame *frame)
179 : wxThread()
180 {
181 m_count = 0;
182 m_frame = frame;
183 }
184
185 void MyThread::WriteText(const wxString& text)
186 {
187 wxString msg;
188
189 // before doing any GUI calls we must ensure that this thread is the only
190 // one doing it!
191
192 wxMutexGuiEnter();
193
194 msg << text;
195 m_frame->WriteText(msg);
196
197 wxMutexGuiLeave();
198 }
199
200 void MyThread::OnExit()
201 {
202 wxCriticalSectionLocker locker(wxGetApp().m_critsect);
203
204 wxArrayThread& threads = wxGetApp().m_threads;
205 threads.Remove(this);
206
207 if ( threads.IsEmpty() )
208 {
209 // signal the main thread that there are no more threads left if it is
210 // waiting for us
211 if ( wxGetApp().m_waitingUntilAllDone )
212 {
213 wxGetApp().m_waitingUntilAllDone = FALSE;
214
215 wxGetApp().m_semAllDone.Post();
216 }
217 }
218 }
219
220 void *MyThread::Entry()
221 {
222 wxString text;
223
224 text.Printf(wxT("Thread 0x%lx started (priority = %u).\n"),
225 GetId(), GetPriority());
226 WriteText(text);
227 // wxLogMessage(text); -- test wxLog thread safeness
228
229 for ( m_count = 0; m_count < 10; m_count++ )
230 {
231 // check if we were asked to exit
232 if ( TestDestroy() )
233 break;
234
235 text.Printf(wxT("[%u] Thread 0x%lx here.\n"), m_count, GetId());
236 WriteText(text);
237
238 // wxSleep() can't be called from non-GUI thread!
239 wxThread::Sleep(1000);
240 }
241
242 text.Printf(wxT("Thread 0x%lx finished.\n"), GetId());
243 WriteText(text);
244 // wxLogMessage(text); -- test wxLog thread safeness
245
246 return NULL;
247 }
248
249 // ----------------------------------------------------------------------------
250 // worker thread
251 // ----------------------------------------------------------------------------
252
253 class MyWorkerThread : public wxThread
254 {
255 public:
256 MyWorkerThread(MyFrame *frame);
257
258 // thread execution starts here
259 virtual void *Entry();
260
261 // called when the thread exits - whether it terminates normally or is
262 // stopped with Delete() (but not when it is Kill()ed!)
263 virtual void OnExit();
264
265 public:
266 MyFrame *m_frame;
267 size_t m_count;
268 };
269
270 MyWorkerThread::MyWorkerThread(MyFrame *frame)
271 : wxThread()
272 {
273 m_frame = frame;
274 m_count = 0;
275 }
276
277 void MyWorkerThread::OnExit()
278 {
279 }
280
281 void *MyWorkerThread::Entry()
282 {
283 for ( m_count = 0; !m_frame->Cancelled() && (m_count < 100); m_count++ )
284 {
285 // check if we were asked to exit
286 if ( TestDestroy() )
287 break;
288
289 // create any type of command event here
290 wxCommandEvent event( wxEVT_COMMAND_MENU_SELECTED, WORKER_EVENT );
291 event.SetInt( m_count );
292
293 // send in a thread-safe way
294 wxPostEvent( m_frame, event );
295
296 // wxSleep() can't be called from non-main thread!
297 wxThread::Sleep(200);
298 }
299
300 wxCommandEvent event( wxEVT_COMMAND_MENU_SELECTED, WORKER_EVENT );
301 event.SetInt(-1); // that's all
302 wxPostEvent( m_frame, event );
303
304 return NULL;
305 }
306
307 // ----------------------------------------------------------------------------
308 // a thread which simply calls wxExecute
309 // ----------------------------------------------------------------------------
310
311 class MyExecThread : public wxThread
312 {
313 public:
314 MyExecThread(const wxChar *command) : wxThread(wxTHREAD_JOINABLE),
315 m_command(command)
316 {
317 Create();
318 }
319
320 virtual ExitCode Entry()
321 {
322 return (ExitCode)EXEC(m_command);
323 }
324
325 private:
326 wxString m_command;
327 };
328
329 // ----------------------------------------------------------------------------
330 // implementation
331 // ----------------------------------------------------------------------------
332
333 BEGIN_EVENT_TABLE(MyFrame, wxFrame)
334 EVT_MENU(THREAD_QUIT, MyFrame::OnQuit)
335 EVT_MENU(THREAD_CLEAR, MyFrame::OnClear)
336 EVT_MENU(THREAD_START_THREAD, MyFrame::OnStartThread)
337 EVT_MENU(THREAD_START_THREADS, MyFrame::OnStartThreads)
338 EVT_MENU(THREAD_STOP_THREAD, MyFrame::OnStopThread)
339 EVT_MENU(THREAD_PAUSE_THREAD, MyFrame::OnPauseThread)
340 EVT_MENU(THREAD_RESUME_THREAD, MyFrame::OnResumeThread)
341
342 EVT_MENU(THREAD_EXEC_MAIN, MyFrame::OnExecMain)
343 EVT_MENU(THREAD_EXEC_THREAD, MyFrame::OnExecThread)
344
345 EVT_MENU(THREAD_SHOWCPUS, MyFrame::OnShowCPUs)
346 EVT_MENU(THREAD_ABOUT, MyFrame::OnAbout)
347
348 EVT_UPDATE_UI(THREAD_START_WORKER, MyFrame::OnUpdateWorker)
349 EVT_MENU(THREAD_START_WORKER, MyFrame::OnStartWorker)
350 EVT_MENU(WORKER_EVENT, MyFrame::OnWorkerEvent)
351
352 EVT_IDLE(MyFrame::OnIdle)
353 END_EVENT_TABLE()
354
355 MyApp::MyApp()
356 : m_semAllDone()
357 {
358 m_waitingUntilAllDone = FALSE;
359 }
360
361 MyApp::~MyApp()
362 {
363 }
364
365 // `Main program' equivalent, creating windows and returning main app frame
366 bool MyApp::OnInit()
367 {
368 // uncomment this to get some debugging messages from the trace code
369 // on the console (or just set WXTRACE env variable to include "thread")
370 //wxLog::AddTraceMask("thread");
371
372 // Create the main frame window
373 MyFrame *frame = new MyFrame((wxFrame *)NULL, _T("wxWindows threads sample"),
374 50, 50, 450, 340);
375
376 // Make a menubar
377 wxMenuBar *menuBar = new wxMenuBar;
378
379 wxMenu *menuFile = new wxMenu;
380 menuFile->Append(THREAD_CLEAR, _T("&Clear log\tCtrl-L"));
381 menuFile->AppendSeparator();
382 menuFile->Append(THREAD_QUIT, _T("E&xit\tAlt-X"));
383 menuBar->Append(menuFile, _T("&File"));
384
385 wxMenu *menuThread = new wxMenu;
386 menuThread->Append(THREAD_START_THREAD, _T("&Start a new thread\tCtrl-N"));
387 menuThread->Append(THREAD_START_THREADS, _T("Start &many threads at once"));
388 menuThread->Append(THREAD_STOP_THREAD, _T("S&top a running thread\tCtrl-S"));
389 menuThread->AppendSeparator();
390 menuThread->Append(THREAD_PAUSE_THREAD, _T("&Pause a running thread\tCtrl-P"));
391 menuThread->Append(THREAD_RESUME_THREAD, _T("&Resume suspended thread\tCtrl-R"));
392 menuThread->AppendSeparator();
393 menuThread->Append(THREAD_START_WORKER, _T("Start &worker thread\tCtrl-W"));
394 menuBar->Append(menuThread, _T("&Thread"));
395
396 wxMenu *menuExec = new wxMenu;
397 menuExec->Append(THREAD_EXEC_MAIN, _T("&Launch a program from main thread\tF5"));
398 menuExec->Append(THREAD_EXEC_THREAD, _T("L&aunch a program from a thread\tCtrl-F5"));
399 menuBar->Append(menuExec, _T("&Execute"));
400
401 wxMenu *menuHelp = new wxMenu;
402 menuHelp->Append(THREAD_SHOWCPUS, _T("&Show CPU count"));
403 menuHelp->AppendSeparator();
404 menuHelp->Append(THREAD_ABOUT, _T("&About..."));
405 menuBar->Append(menuHelp, _T("&Help"));
406
407 frame->SetMenuBar(menuBar);
408
409 // Show the frame
410 frame->Show(TRUE);
411
412 SetTopWindow(frame);
413
414 return TRUE;
415 }
416
417 // My frame constructor
418 MyFrame::MyFrame(wxFrame *frame, const wxString& title,
419 int x, int y, int w, int h)
420 : wxFrame(frame, -1, title, wxPoint(x, y), wxSize(w, h))
421 {
422 m_nRunning = m_nCount = 0;
423
424 m_dlgProgress = (wxProgressDialog *)NULL;
425
426 CreateStatusBar(2);
427
428 m_txtctrl = new wxTextCtrl(this, -1, _T(""), wxPoint(0, 0), wxSize(0, 0),
429 wxTE_MULTILINE | wxTE_READONLY);
430
431 }
432
433 MyFrame::~MyFrame()
434 {
435 // NB: although the OS will terminate all the threads anyhow when the main
436 // one exits, it's good practice to do it ourselves -- even if it's not
437 // completely trivial in this example
438
439 // tell all the threads to terminate: note that they can't terminate while
440 // we're deleting them because they will block in their OnExit() -- this is
441 // important as otherwise we might access invalid array elements
442 wxThread *thread;
443
444 wxGetApp().m_critsect.Enter();
445
446 // check if we have any threads running first
447 const wxArrayThread& threads = wxGetApp().m_threads;
448 size_t count = threads.GetCount();
449
450 if ( count )
451 {
452 // set the flag for MyThread::OnExit()
453 wxGetApp().m_waitingUntilAllDone = TRUE;
454
455 // stop all threads
456 while ( ! threads.IsEmpty() )
457 {
458 thread = threads.Last();
459
460 wxGetApp().m_critsect.Leave();
461
462 thread->Delete();
463
464 wxGetApp().m_critsect.Enter();
465 }
466 }
467
468 wxGetApp().m_critsect.Leave();
469
470 if ( count )
471 {
472 // now wait for them to really terminate
473 wxGetApp().m_semAllDone.Wait();
474 }
475 //else: no threads to terminate, no condition to wait for
476 }
477
478 MyThread *MyFrame::CreateThread()
479 {
480 MyThread *thread = new MyThread(this);
481
482 if ( thread->Create() != wxTHREAD_NO_ERROR )
483 {
484 wxLogError(wxT("Can't create thread!"));
485 }
486
487 wxCriticalSectionLocker enter(wxGetApp().m_critsect);
488 wxGetApp().m_threads.Add(thread);
489
490 return thread;
491 }
492
493 void MyFrame::OnStartThreads(wxCommandEvent& WXUNUSED(event) )
494 {
495 static long s_num = 10;
496
497 s_num = wxGetNumberFromUser(_T("How many threads to start: "), _T(""),
498 _T("wxThread sample"), s_num, 1, 10000, this);
499 if ( s_num == -1 )
500 {
501 s_num = 10;
502
503 return;
504 }
505
506 size_t count = (size_t)s_num, n;
507
508 wxArrayThread threads;
509
510 // first create them all...
511 for ( n = 0; n < count; n++ )
512 {
513 wxThread *thr = CreateThread();
514
515 // we want to show the effect of SetPriority(): the first thread will
516 // have the lowest priority, the second - the highest, all the rest
517 // the normal one
518 if ( n == 0 )
519 thr->SetPriority(WXTHREAD_MIN_PRIORITY);
520 else if ( n == 1 )
521 thr->SetPriority(WXTHREAD_MAX_PRIORITY);
522 else
523 thr->SetPriority(WXTHREAD_DEFAULT_PRIORITY);
524
525 threads.Add(thr);
526 }
527
528 wxString msg;
529 msg.Printf(wxT("%d new threads created."), count);
530 SetStatusText(msg, 1);
531
532 // ...and then start them
533 for ( n = 0; n < count; n++ )
534 {
535 threads[n]->Run();
536 }
537 }
538
539 void MyFrame::OnStartThread(wxCommandEvent& WXUNUSED(event) )
540 {
541 MyThread *thread = CreateThread();
542
543 if ( thread->Run() != wxTHREAD_NO_ERROR )
544 {
545 wxLogError(wxT("Can't start thread!"));
546 }
547
548 SetStatusText(_T("New thread started."), 1);
549 }
550
551 void MyFrame::OnStopThread(wxCommandEvent& WXUNUSED(event) )
552 {
553 wxGetApp().m_critsect.Enter();
554
555 // stop the last thread
556 if ( wxGetApp().m_threads.IsEmpty() )
557 {
558 wxLogError(wxT("No thread to stop!"));
559
560 wxGetApp().m_critsect.Leave();
561 }
562 else
563 {
564 wxThread *thread = wxGetApp().m_threads.Last();
565
566 // it's important to leave critical section before calling Delete()
567 // because delete will (implicitly) call OnExit() which also tries
568 // to enter the same crit section - would dead lock.
569 wxGetApp().m_critsect.Leave();
570
571 thread->Delete();
572
573 SetStatusText(_T("Thread stopped."), 1);
574 }
575 }
576
577 void MyFrame::OnResumeThread(wxCommandEvent& WXUNUSED(event) )
578 {
579 wxCriticalSectionLocker enter(wxGetApp().m_critsect);
580
581 // resume first suspended thread
582 size_t n = 0, count = wxGetApp().m_threads.Count();
583 while ( n < count && !wxGetApp().m_threads[n]->IsPaused() )
584 n++;
585
586 if ( n == count )
587 {
588 wxLogError(wxT("No thread to resume!"));
589 }
590 else
591 {
592 wxGetApp().m_threads[n]->Resume();
593
594 SetStatusText(_T("Thread resumed."), 1);
595 }
596 }
597
598 void MyFrame::OnPauseThread(wxCommandEvent& WXUNUSED(event) )
599 {
600 wxCriticalSectionLocker enter(wxGetApp().m_critsect);
601
602 // pause last running thread
603 int n = wxGetApp().m_threads.Count() - 1;
604 while ( n >= 0 && !wxGetApp().m_threads[n]->IsRunning() )
605 n--;
606
607 if ( n < 0 )
608 {
609 wxLogError(wxT("No thread to pause!"));
610 }
611 else
612 {
613 wxGetApp().m_threads[n]->Pause();
614
615 SetStatusText(_T("Thread paused."), 1);
616 }
617 }
618
619 // set the frame title indicating the current number of threads
620 void MyFrame::OnIdle(wxIdleEvent& event)
621 {
622 wxCriticalSectionLocker enter(wxGetApp().m_critsect);
623
624 // update the counts of running/total threads
625 size_t nRunning = 0,
626 nCount = wxGetApp().m_threads.Count();
627 for ( size_t n = 0; n < nCount; n++ )
628 {
629 if ( wxGetApp().m_threads[n]->IsRunning() )
630 nRunning++;
631 }
632
633 if ( nCount != m_nCount || nRunning != m_nRunning )
634 {
635 m_nRunning = nRunning;
636 m_nCount = nCount;
637
638 wxLogStatus(this, wxT("%u threads total, %u running."), nCount, nRunning);
639 }
640 //else: avoid flicker - don't print anything
641
642 event.Skip();
643 }
644
645 void MyFrame::OnQuit(wxCommandEvent& WXUNUSED(event) )
646 {
647 Close(TRUE);
648 }
649
650 void MyFrame::OnExecMain(wxCommandEvent& WXUNUSED(event))
651 {
652 wxLogMessage(wxT("The exit code from the main program is %ld"),
653 EXEC(_T("/bin/echo \"main program\"")));
654 }
655
656 void MyFrame::OnExecThread(wxCommandEvent& WXUNUSED(event))
657 {
658 MyExecThread thread(wxT("/bin/echo \"child thread\""));
659 thread.Run();
660
661 wxLogMessage(wxT("The exit code from a child thread is %ld"),
662 (long)thread.Wait());
663 }
664
665 void MyFrame::OnShowCPUs(wxCommandEvent& WXUNUSED(event))
666 {
667 wxString msg;
668
669 int nCPUs = wxThread::GetCPUCount();
670 switch ( nCPUs )
671 {
672 case -1:
673 msg = _T("Unknown number of CPUs");
674 break;
675
676 case 0:
677 msg = _T("WARNING: you're running without any CPUs!");
678 break;
679
680 case 1:
681 msg = _T("This system only has one CPU.");
682 break;
683
684 default:
685 msg.Printf(wxT("This system has %d CPUs"), nCPUs);
686 }
687
688 wxLogMessage(msg);
689 }
690
691 void MyFrame::OnAbout(wxCommandEvent& WXUNUSED(event) )
692 {
693 wxMessageDialog dialog(this,
694 _T("wxWindows multithreaded application sample\n")
695 _T("(c) 1998 Julian Smart, Guilhem Lavaux\n")
696 _T("(c) 1999 Vadim Zeitlin\n")
697 _T("(c) 2000 Robert Roebling"),
698 _T("About wxThread sample"),
699 wxOK | wxICON_INFORMATION);
700
701 dialog.ShowModal();
702 }
703
704 void MyFrame::OnClear(wxCommandEvent& WXUNUSED(event))
705 {
706 m_txtctrl->Clear();
707 }
708
709 void MyFrame::OnUpdateWorker(wxUpdateUIEvent& event)
710 {
711 event.Enable( m_dlgProgress == NULL );
712 }
713
714 void MyFrame::OnStartWorker(wxCommandEvent& WXUNUSED(event))
715 {
716 MyWorkerThread *thread = new MyWorkerThread(this);
717
718 if ( thread->Create() != wxTHREAD_NO_ERROR )
719 {
720 wxLogError(wxT("Can't create thread!"));
721 }
722
723 m_dlgProgress = new wxProgressDialog
724 (
725 _T("Progress dialog"),
726 _T("Wait until the thread terminates or press [Cancel]"),
727 100,
728 this,
729 wxPD_CAN_ABORT |
730 wxPD_APP_MODAL |
731 wxPD_ELAPSED_TIME |
732 wxPD_ESTIMATED_TIME |
733 wxPD_REMAINING_TIME
734 );
735
736 // thread is not running yet, no need for crit sect
737 m_cancelled = FALSE;
738
739 thread->Run();
740 }
741
742 void MyFrame::OnWorkerEvent(wxCommandEvent& event)
743 {
744 #if 0
745 WriteText( _T("Got message from worker thread: ") );
746 WriteText( event.GetString() );
747 WriteText( _T("\n") );
748 #else
749 int n = event.GetInt();
750 if ( n == -1 )
751 {
752 m_dlgProgress->Destroy();
753 m_dlgProgress = (wxProgressDialog *)NULL;
754
755 // the dialog is aborted because the event came from another thread, so
756 // we may need to wake up the main event loop for the dialog to be
757 // really closed
758 wxWakeUpIdle();
759 }
760 else
761 {
762 if ( !m_dlgProgress->Update(n) )
763 {
764 wxCriticalSectionLocker lock(m_critsectWork);
765
766 m_cancelled = TRUE;
767 }
768 }
769 #endif
770 }
771
772 bool MyFrame::Cancelled()
773 {
774 wxCriticalSectionLocker lock(m_critsectWork);
775
776 return m_cancelled;
777 }