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