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