]> git.saurik.com Git - wxWidgets.git/blob - samples/thread/test.cpp
fixed bug in handling quoted characters in value names
[wxWidgets.git] / samples / thread / test.cpp
1 /////////////////////////////////////////////////////////////////////////////
2 // Name: test.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 "test.cpp"
19 #pragma interface "test.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 class MyThread;
44 WX_DEFINE_ARRAY(wxThread *, wxArrayThread);
45
46 // Define a new application type
47 class MyApp : public wxApp
48 {
49 public:
50 virtual bool OnInit();
51
52 public:
53 // all the threads currently alive - as soon as the thread terminates, it's
54 // removed from the array
55 wxArrayThread m_threads;
56
57 // crit section protects access to all of the arrays below
58 wxCriticalSection m_critsect;
59 };
60
61 // Create a new application object
62 IMPLEMENT_APP(MyApp)
63
64 // Define a new frame type
65 class MyFrame: public wxFrame
66 {
67 public:
68 // ctor
69 MyFrame(wxFrame *frame, const wxString& title, int x, int y, int w, int h);
70
71 // operations
72 void WriteText(const wxString& text) { m_txtctrl->WriteText(text); }
73
74 // accessors for MyWorkerThread (called in its context!)
75 bool Cancelled();
76
77 // callbacks
78 void OnQuit(wxCommandEvent& event);
79 void OnAbout(wxCommandEvent& event);
80 void OnClear(wxCommandEvent& event);
81
82 void OnStartThread(wxCommandEvent& event);
83 void OnStartThreads(wxCommandEvent& event);
84 void OnStopThread(wxCommandEvent& event);
85 void OnPauseThread(wxCommandEvent& event);
86 void OnResumeThread(wxCommandEvent& event);
87
88 void OnStartWorker(wxCommandEvent& event);
89 void OnWorkerEvent(wxCommandEvent& event);
90 void OnUpdateWorker(wxUpdateUIEvent& event);
91
92 void OnIdle(wxIdleEvent &event);
93
94 private:
95 // helper function - creates a new thread (but doesn't run it)
96 MyThread *CreateThread();
97
98 // just some place to put our messages in
99 wxTextCtrl *m_txtctrl;
100
101 // remember the number of running threads and total number of threads
102 size_t m_nRunning, m_nCount;
103
104 // the progress dialog which we show while worker thread is running
105 wxProgressDialog *m_dlgProgress;
106
107 // was the worker thread cancelled by user?
108 bool m_cancelled;
109
110 // protects m_cancelled
111 wxCriticalSection m_critsectWork;
112
113 DECLARE_EVENT_TABLE()
114 };
115
116 // ID for the menu commands
117 enum
118 {
119 TEST_QUIT = 1,
120 TEST_TEXT = 101,
121 TEST_ABOUT,
122 TEST_CLEAR,
123 TEST_START_THREAD = 201,
124 TEST_START_THREADS,
125 TEST_STOP_THREAD,
126 TEST_PAUSE_THREAD,
127 TEST_RESUME_THREAD,
128 TEST_START_WORKER,
129 WORKER_EVENT // this one gets sent from the worker thread
130 };
131
132 //--------------------------------------------------
133 // GUI thread
134 //--------------------------------------------------
135
136 class MyThread : public wxThread
137 {
138 public:
139 MyThread(MyFrame *frame);
140
141 // thread execution starts here
142 virtual void *Entry();
143
144 // called when the thread exits - whether it terminates normally or is
145 // stopped with Delete() (but not when it is Kill()ed!)
146 virtual void OnExit();
147
148 // write something to the text control
149 void WriteText(const wxString& text);
150
151 public:
152 size_t m_count;
153 MyFrame *m_frame;
154 };
155
156 MyThread::MyThread(MyFrame *frame)
157 : wxThread()
158 {
159 m_count = 0;
160 m_frame = frame;
161 }
162
163 void MyThread::WriteText(const wxString& text)
164 {
165 wxString msg;
166
167 // before doing any GUI calls we must ensure that this thread is the only
168 // one doing it!
169
170 wxMutexGuiEnter();
171
172 msg << text;
173 m_frame->WriteText(msg);
174
175 wxMutexGuiLeave();
176 }
177
178 void MyThread::OnExit()
179 {
180 wxCriticalSectionLocker locker(wxGetApp().m_critsect);
181
182 wxGetApp().m_threads.Remove(this);
183 }
184
185 void *MyThread::Entry()
186 {
187 wxString text;
188
189 text.Printf("Thread 0x%x started (priority = %d).\n",
190 GetId(), GetPriority());
191 WriteText(text);
192
193 for ( m_count = 0; m_count < 10; m_count++ )
194 {
195 // check if we were asked to exit
196 if ( TestDestroy() )
197 break;
198
199 text.Printf("[%u] Thread 0x%x here.\n", m_count, GetId());
200 WriteText(text);
201
202 // wxSleep() can't be called from non-GUI thread!
203 wxThread::Sleep(1000);
204 }
205
206 text.Printf("Thread 0x%x finished.\n", GetId());
207 WriteText(text);
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("[%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 // Create the main frame window
302 MyFrame *frame = new MyFrame((wxFrame *)NULL, "wxWindows threads sample",
303 50, 50, 450, 340);
304
305 // Make a menubar
306 wxMenu *file_menu = new wxMenu;
307
308 file_menu->Append(TEST_CLEAR, "&Clear log\tCtrl-L");
309 file_menu->AppendSeparator();
310 file_menu->Append(TEST_ABOUT, "&About");
311 file_menu->AppendSeparator();
312 file_menu->Append(TEST_QUIT, "E&xit\tAlt-X");
313 wxMenuBar *menu_bar = new wxMenuBar;
314 menu_bar->Append(file_menu, "&File");
315
316 wxMenu *thread_menu = new wxMenu;
317 thread_menu->Append(TEST_START_THREAD, "&Start a new thread\tCtrl-N");
318 thread_menu->Append(TEST_START_THREADS, "Start &many threads at once");
319 thread_menu->Append(TEST_STOP_THREAD, "S&top a running thread\tCtrl-S");
320 thread_menu->AppendSeparator();
321 thread_menu->Append(TEST_PAUSE_THREAD, "&Pause a running thread\tCtrl-P");
322 thread_menu->Append(TEST_RESUME_THREAD, "&Resume suspended thread\tCtrl-R");
323 thread_menu->AppendSeparator();
324 thread_menu->Append(TEST_START_WORKER, "Start &worker thread\tCtrl-W");
325
326 menu_bar->Append(thread_menu, "&Thread");
327 frame->SetMenuBar(menu_bar);
328
329 // Show the frame
330 frame->Show(TRUE);
331
332 SetTopWindow(frame);
333
334 return TRUE;
335 }
336
337 // My frame constructor
338 MyFrame::MyFrame(wxFrame *frame, const wxString& title,
339 int x, int y, int w, int h)
340 : wxFrame(frame, -1, title, wxPoint(x, y), wxSize(w, h))
341 {
342 m_nRunning = m_nCount = 0;
343
344 m_dlgProgress = (wxProgressDialog *)NULL;
345
346 CreateStatusBar(2);
347
348 m_txtctrl = new wxTextCtrl(this, -1, "", wxPoint(0, 0), wxSize(0, 0),
349 wxTE_MULTILINE | wxTE_READONLY);
350
351 }
352
353 MyThread *MyFrame::CreateThread()
354 {
355 MyThread *thread = new MyThread(this);
356
357 if ( thread->Create() != wxTHREAD_NO_ERROR )
358 {
359 wxLogError("Can't create thread!");
360 }
361
362 wxCriticalSectionLocker enter(wxGetApp().m_critsect);
363 wxGetApp().m_threads.Add(thread);
364
365 return thread;
366 }
367
368 void MyFrame::OnStartThreads(wxCommandEvent& WXUNUSED(event) )
369 {
370 static long s_num = 10;
371
372 s_num = wxGetNumberFromUser("How many threads to start: ", "",
373 "wxThread sample", s_num, 1, 10000, this);
374 if ( s_num == -1 )
375 {
376 s_num = 10;
377
378 return;
379 }
380
381 size_t count = (size_t)s_num, n;
382
383 wxArrayThread threads;
384
385 // first create them all...
386 for ( n = 0; n < count; n++ )
387 {
388 wxThread *thr = CreateThread();
389
390 // we want to show the effect of SetPriority(): the first thread will
391 // have the lowest priority, the second - the highest, all the rest
392 // the normal one
393 if ( n == 0 )
394 thr->SetPriority(WXTHREAD_MIN_PRIORITY);
395 else if ( n == 1 )
396 thr->SetPriority(WXTHREAD_MAX_PRIORITY);
397 else
398 thr->SetPriority(WXTHREAD_DEFAULT_PRIORITY);
399
400 threads.Add(thr);
401 }
402
403 wxString msg;
404 msg.Printf("%d new threads created.", count);
405 SetStatusText(msg, 1);
406
407 // ...and then start them
408 for ( n = 0; n < count; n++ )
409 {
410 threads[n]->Run();
411 }
412 }
413
414 void MyFrame::OnStartThread(wxCommandEvent& WXUNUSED(event) )
415 {
416 MyThread *thread = CreateThread();
417
418 if ( thread->Run() != wxTHREAD_NO_ERROR )
419 {
420 wxLogError("Can't start thread!");
421 }
422
423 SetStatusText("New thread started.", 1);
424 }
425
426 void MyFrame::OnStopThread(wxCommandEvent& WXUNUSED(event) )
427 {
428 // stop the last thread
429 if ( wxGetApp().m_threads.IsEmpty() )
430 {
431 wxLogError("No thread to stop!");
432 }
433 else
434 {
435 wxGetApp().m_critsect.Enter();
436
437 wxThread *thread = wxGetApp().m_threads.Last();
438
439 // it's important to leave critical section before calling Delete()
440 // because delete will (implicitly) call OnExit() which also tries
441 // to enter the same crit section - would dead lock.
442 wxGetApp().m_critsect.Leave();
443
444 thread->Delete();
445
446 SetStatusText("Thread stopped.", 1);
447 }
448 }
449
450 void MyFrame::OnResumeThread(wxCommandEvent& WXUNUSED(event) )
451 {
452 wxCriticalSectionLocker enter(wxGetApp().m_critsect);
453
454 // resume first suspended thread
455 size_t n = 0, count = wxGetApp().m_threads.Count();
456 while ( n < count && !wxGetApp().m_threads[n]->IsPaused() )
457 n++;
458
459 if ( n == count )
460 {
461 wxLogError("No thread to resume!");
462 }
463 else
464 {
465 wxGetApp().m_threads[n]->Resume();
466
467 SetStatusText("Thread resumed.", 1);
468 }
469 }
470
471 void MyFrame::OnPauseThread(wxCommandEvent& WXUNUSED(event) )
472 {
473 wxCriticalSectionLocker enter(wxGetApp().m_critsect);
474
475 // pause last running thread
476 int n = wxGetApp().m_threads.Count() - 1;
477 while ( n >= 0 && !wxGetApp().m_threads[n]->IsRunning() )
478 n--;
479
480 if ( n < 0 )
481 {
482 wxLogError("No thread to pause!");
483 }
484 else
485 {
486 wxGetApp().m_threads[n]->Pause();
487
488 SetStatusText("Thread paused.", 1);
489 }
490 }
491
492 // set the frame title indicating the current number of threads
493 void MyFrame::OnIdle(wxIdleEvent &event)
494 {
495 // update the counts of running/total threads
496 size_t nRunning = 0,
497 nCount = wxGetApp().m_threads.Count();
498 for ( size_t n = 0; n < nCount; n++ )
499 {
500 if ( wxGetApp().m_threads[n]->IsRunning() )
501 nRunning++;
502 }
503
504 if ( nCount != m_nCount || nRunning != m_nRunning )
505 {
506 m_nRunning = nRunning;
507 m_nCount = nCount;
508
509 wxLogStatus(this, "%u threads total, %u running.", nCount, nRunning);
510 }
511 //else: avoid flicker - don't print anything
512 }
513
514 void MyFrame::OnQuit(wxCommandEvent& WXUNUSED(event) )
515 {
516 size_t count = wxGetApp().m_threads.Count();
517 for ( size_t i = 0; i < count; i++ )
518 {
519 wxGetApp().m_threads[0]->Delete();
520 }
521
522 Close(TRUE);
523 }
524
525 void MyFrame::OnAbout(wxCommandEvent& WXUNUSED(event) )
526 {
527 wxMessageDialog dialog(this, "wxWindows multithreaded application sample\n"
528 "(c) 1998 Julian Smart, Guilhem Lavaux\n"
529 "(c) 1999 Vadim Zeitlin\n"
530 "(c) 2000 Robert Roebling",
531 "About wxThread sample",
532 wxOK | wxICON_INFORMATION);
533
534 dialog.ShowModal();
535 }
536
537 void MyFrame::OnClear(wxCommandEvent& WXUNUSED(event))
538 {
539 m_txtctrl->Clear();
540 }
541
542 void MyFrame::OnUpdateWorker(wxUpdateUIEvent& event)
543 {
544 event.Enable( m_dlgProgress == NULL );
545 }
546
547 void MyFrame::OnStartWorker(wxCommandEvent& WXUNUSED(event))
548 {
549 MyWorkerThread *thread = new MyWorkerThread(this);
550
551 if ( thread->Create() != wxTHREAD_NO_ERROR )
552 {
553 wxLogError("Can't create thread!");
554 }
555
556 m_dlgProgress = new wxProgressDialog
557 (
558 "Progress dialog",
559 "Wait until the thread terminates or press [Cancel]",
560 100,
561 this,
562 wxPD_CAN_ABORT |
563 wxPD_APP_MODAL |
564 wxPD_ELAPSED_TIME |
565 wxPD_ESTIMATED_TIME |
566 wxPD_REMAINING_TIME
567 );
568
569 // thread is not running yet, no need for crit sect
570 m_cancelled = FALSE;
571
572 thread->Run();
573 }
574
575 void MyFrame::OnWorkerEvent(wxCommandEvent& event)
576 {
577 #if 0
578 WriteText( "Got message from worker thread: " );
579 WriteText( event.GetString() );
580 WriteText( "\n" );
581 #else
582 int n = event.GetInt();
583 if ( n == -1 )
584 {
585 m_dlgProgress->Destroy();
586 m_dlgProgress = (wxProgressDialog *)NULL;
587
588 // the dialog is aborted because the event came from another thread, so
589 // we may need to wake up the main event loop for the dialog to be
590 // really closed
591 wxWakeUpIdle();
592 }
593 else
594 {
595 if ( !m_dlgProgress->Update(n) )
596 {
597 wxCriticalSectionLocker lock(m_critsectWork);
598
599 m_cancelled = TRUE;
600 }
601 }
602 #endif
603 }
604
605 bool MyFrame::Cancelled()
606 {
607 wxCriticalSectionLocker lock(m_critsectWork);
608
609 return m_cancelled;
610 }