]> git.saurik.com Git - wxWidgets.git/blob - samples/thread/test.cpp
wxLocale now uses wxEncodingConverter (must be explicitly enabled)
[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 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 // callbacks
73 void OnQuit(wxCommandEvent& event);
74 void OnAbout(wxCommandEvent& event);
75 void OnClear(wxCommandEvent& event);
76
77 void OnStartThread(wxCommandEvent& event);
78 void OnStartThreads(wxCommandEvent& event);
79 void OnStopThread(wxCommandEvent& event);
80 void OnPauseThread(wxCommandEvent& event);
81 void OnResumeThread(wxCommandEvent& event);
82
83 void OnStartWorker(wxCommandEvent& event);
84 void OnWorkerEvent(wxCommandEvent& event);
85
86 void OnIdle(wxIdleEvent &event);
87
88 private:
89 // helper function - creates a new thread (but doesn't run it)
90 MyThread *CreateThread();
91
92 // just some place to put our messages in
93 wxTextCtrl *m_txtctrl;
94
95 // remember the number of running threads and total number of threads
96 size_t m_nRunning, m_nCount;
97
98 DECLARE_EVENT_TABLE()
99 };
100
101 // ID for the menu commands
102 enum
103 {
104 TEST_QUIT = 1,
105 TEST_TEXT = 101,
106 TEST_ABOUT,
107 TEST_CLEAR,
108 TEST_START_THREAD = 201,
109 TEST_START_THREADS,
110 TEST_STOP_THREAD,
111 TEST_PAUSE_THREAD,
112 TEST_RESUME_THREAD,
113 TEST_START_WORKER,
114 WORKER_EVENT // this one gets sent from the worker thread
115 };
116
117 //--------------------------------------------------
118 // GUI thread
119 //--------------------------------------------------
120
121 class MyThread : public wxThread
122 {
123 public:
124 MyThread(MyFrame *frame);
125
126 // thread execution starts here
127 virtual void *Entry();
128
129 // called when the thread exits - whether it terminates normally or is
130 // stopped with Delete() (but not when it is Kill()ed!)
131 virtual void OnExit();
132
133 // write something to the text control
134 void WriteText(const wxString& text);
135
136 public:
137 size_t m_count;
138 MyFrame *m_frame;
139 };
140
141 MyThread::MyThread(MyFrame *frame)
142 : wxThread()
143 {
144 m_count = 0;
145 m_frame = frame;
146 }
147
148 void MyThread::WriteText(const wxString& text)
149 {
150 wxString msg;
151
152 // before doing any GUI calls we must ensure that this thread is the only
153 // one doing it!
154
155 wxMutexGuiEnter();
156
157 msg << text;
158
159 m_frame->WriteText(msg);
160
161 wxMutexGuiLeave();
162 }
163
164 void MyThread::OnExit()
165 {
166 wxCriticalSectionLocker locker(wxGetApp().m_critsect);
167
168 wxGetApp().m_threads.Remove(this);
169 }
170
171 void *MyThread::Entry()
172 {
173 wxString text;
174
175 text.Printf("Thread 0x%x started (priority = %d).\n",
176 GetId(), GetPriority());
177 WriteText(text);
178
179 for ( m_count = 0; m_count < 10; m_count++ )
180 {
181 // check if we were asked to exit
182 if ( TestDestroy() )
183 break;
184
185 text.Printf("[%u] Thread 0x%x here.\n", m_count, GetId());
186 WriteText(text);
187
188 // wxSleep() can't be called from non-GUI thread!
189 wxThread::Sleep(1000);
190 }
191
192 text.Printf("Thread 0x%x finished.\n", GetId());
193 WriteText(text);
194
195 return NULL;
196 }
197
198 //--------------------------------------------------
199 // worker thread
200 //--------------------------------------------------
201
202 class MyWorkerThread : public wxThread
203 {
204 public:
205 MyWorkerThread(MyFrame *frame);
206
207 // thread execution starts here
208 virtual void *Entry();
209
210 // called when the thread exits - whether it terminates normally or is
211 // stopped with Delete() (but not when it is Kill()ed!)
212 virtual void OnExit();
213
214 public:
215 MyFrame *m_frame;
216 size_t m_count;
217 };
218
219 MyWorkerThread::MyWorkerThread(MyFrame *frame)
220 : wxThread()
221 {
222 m_frame = frame;
223 m_count = 0;
224 }
225
226 void MyWorkerThread::OnExit()
227 {
228 }
229
230 void *MyWorkerThread::Entry()
231 {
232 for ( m_count = 0; m_count < 10; m_count++ )
233 {
234 // check if we were asked to exit
235 if ( TestDestroy() )
236 break;
237
238 wxString text;
239 text.Printf("[%u] Thread 0x%x here!!", m_count, GetId());
240
241 // create any type of command event here
242 wxCommandEvent event( wxEVT_COMMAND_MENU_SELECTED, WORKER_EVENT );
243 event.SetInt( WORKER_EVENT );
244 event.SetString( text );
245
246 // send in a thread-safe way
247 wxPostEvent( m_frame, event );
248
249 // same as:
250 // m_frame->AddPendingEvent( event );
251
252 // wxSleep() can't be called from non-main thread!
253 wxThread::Sleep(1000);
254 }
255
256 return NULL;
257 }
258
259 //--------------------------------------------------
260 // main program
261 //--------------------------------------------------
262
263 BEGIN_EVENT_TABLE(MyFrame, wxFrame)
264 EVT_MENU(TEST_QUIT, MyFrame::OnQuit)
265 EVT_MENU(TEST_ABOUT, MyFrame::OnAbout)
266 EVT_MENU(TEST_CLEAR, MyFrame::OnClear)
267 EVT_MENU(TEST_START_THREAD, MyFrame::OnStartThread)
268 EVT_MENU(TEST_START_THREADS, MyFrame::OnStartThreads)
269 EVT_MENU(TEST_STOP_THREAD, MyFrame::OnStopThread)
270 EVT_MENU(TEST_PAUSE_THREAD, MyFrame::OnPauseThread)
271 EVT_MENU(TEST_RESUME_THREAD, MyFrame::OnResumeThread)
272
273 EVT_MENU(TEST_START_WORKER, MyFrame::OnStartWorker)
274 EVT_MENU(WORKER_EVENT, MyFrame::OnWorkerEvent)
275
276 EVT_IDLE(MyFrame::OnIdle)
277 END_EVENT_TABLE()
278
279 // `Main program' equivalent, creating windows and returning main app frame
280 bool MyApp::OnInit()
281 {
282 // Create the main frame window
283 MyFrame *frame = new MyFrame((wxFrame *)NULL, "wxWindows threads sample",
284 50, 50, 450, 340);
285
286 // Make a menubar
287 wxMenu *file_menu = new wxMenu;
288
289 file_menu->Append(TEST_CLEAR, "&Clear log\tCtrl-L");
290 file_menu->AppendSeparator();
291 file_menu->Append(TEST_ABOUT, "&About");
292 file_menu->AppendSeparator();
293 file_menu->Append(TEST_QUIT, "E&xit\tAlt-X");
294 wxMenuBar *menu_bar = new wxMenuBar;
295 menu_bar->Append(file_menu, "&File");
296
297 wxMenu *thread_menu = new wxMenu;
298 thread_menu->Append(TEST_START_THREAD, "&Start a new thread\tCtrl-N");
299 thread_menu->Append(TEST_START_THREADS, "Start &many threads at once");
300 thread_menu->Append(TEST_STOP_THREAD, "S&top a running thread\tCtrl-S");
301 thread_menu->AppendSeparator();
302 thread_menu->Append(TEST_PAUSE_THREAD, "&Pause a running thread\tCtrl-P");
303 thread_menu->Append(TEST_RESUME_THREAD, "&Resume suspended thread\tCtrl-R");
304 thread_menu->AppendSeparator();
305 thread_menu->Append(TEST_START_WORKER, "Start &worker thread\tCtrl-W");
306
307 menu_bar->Append(thread_menu, "&Thread");
308 frame->SetMenuBar(menu_bar);
309
310 // Show the frame
311 frame->Show(TRUE);
312
313 SetTopWindow(frame);
314
315 return TRUE;
316 }
317
318 // My frame constructor
319 MyFrame::MyFrame(wxFrame *frame, const wxString& title,
320 int x, int y, int w, int h)
321 : wxFrame(frame, -1, title, wxPoint(x, y), wxSize(w, h))
322 {
323 m_nRunning = m_nCount = 0;
324
325 CreateStatusBar(2);
326
327 m_txtctrl = new wxTextCtrl(this, -1, "", wxPoint(0, 0), wxSize(0, 0),
328 wxTE_MULTILINE | wxTE_READONLY);
329
330 }
331
332 MyThread *MyFrame::CreateThread()
333 {
334 MyThread *thread = new MyThread(this);
335
336 if ( thread->Create() != wxTHREAD_NO_ERROR )
337 {
338 wxLogError("Can't create thread!");
339 }
340
341 wxCriticalSectionLocker enter(wxGetApp().m_critsect);
342 wxGetApp().m_threads.Add(thread);
343
344 return thread;
345 }
346
347 void MyFrame::OnStartThreads(wxCommandEvent& WXUNUSED(event) )
348 {
349 static long s_num = 10;
350
351 s_num = wxGetNumberFromUser("How many threads to start: ", "",
352 "wxThread sample", s_num, 1, 10000, this);
353 if ( s_num == -1 )
354 {
355 s_num = 10;
356
357 return;
358 }
359
360 size_t count = (size_t)s_num, n;
361
362 wxArrayThread threads;
363
364 // first create them all...
365 for ( n = 0; n < count; n++ )
366 {
367 wxThread *thr = CreateThread();
368
369 // we want to show the effect of SetPriority(): the first thread will
370 // have the lowest priority, the second - the highest, all the rest
371 // the normal one
372 if ( n == 0 )
373 thr->SetPriority(WXTHREAD_MIN_PRIORITY);
374 else if ( n == 1 )
375 thr->SetPriority(WXTHREAD_MAX_PRIORITY);
376 else
377 thr->SetPriority(WXTHREAD_DEFAULT_PRIORITY);
378
379 threads.Add(thr);
380 }
381
382 wxString msg;
383 msg.Printf("%d new threads created.", count);
384 SetStatusText(msg, 1);
385
386 // ...and then start them
387 for ( n = 0; n < count; n++ )
388 {
389 threads[n]->Run();
390 }
391 }
392
393 void MyFrame::OnStartThread(wxCommandEvent& WXUNUSED(event) )
394 {
395 MyThread *thread = CreateThread();
396
397 if ( thread->Run() != wxTHREAD_NO_ERROR )
398 {
399 wxLogError("Can't start thread!");
400 }
401
402 SetStatusText("New thread started.", 1);
403 }
404
405 void MyFrame::OnStopThread(wxCommandEvent& WXUNUSED(event) )
406 {
407 // stop the last thread
408 if ( wxGetApp().m_threads.IsEmpty() )
409 {
410 wxLogError("No thread to stop!");
411 }
412 else
413 {
414 wxGetApp().m_critsect.Enter();
415
416 wxThread *thread = wxGetApp().m_threads.Last();
417
418 // it's important to leave critical section before calling Delete()
419 // because delete will (implicitly) call OnExit() which also tries
420 // to enter the same crit section - would dead lock.
421 wxGetApp().m_critsect.Leave();
422
423 thread->Delete();
424
425 SetStatusText("Thread stopped.", 1);
426 }
427 }
428
429 void MyFrame::OnResumeThread(wxCommandEvent& WXUNUSED(event) )
430 {
431 wxCriticalSectionLocker enter(wxGetApp().m_critsect);
432
433 // resume first suspended thread
434 size_t n = 0, count = wxGetApp().m_threads.Count();
435 while ( n < count && !wxGetApp().m_threads[n]->IsPaused() )
436 n++;
437
438 if ( n == count )
439 {
440 wxLogError("No thread to resume!");
441 }
442 else
443 {
444 wxGetApp().m_threads[n]->Resume();
445
446 SetStatusText("Thread resumed.", 1);
447 }
448 }
449
450 void MyFrame::OnPauseThread(wxCommandEvent& WXUNUSED(event) )
451 {
452 wxCriticalSectionLocker enter(wxGetApp().m_critsect);
453
454 // pause last running thread
455 int n = wxGetApp().m_threads.Count() - 1;
456 while ( n >= 0 && !wxGetApp().m_threads[n]->IsRunning() )
457 n--;
458
459 if ( n < 0 )
460 {
461 wxLogError("No thread to pause!");
462 }
463 else
464 {
465 wxGetApp().m_threads[n]->Pause();
466
467 SetStatusText("Thread paused.", 1);
468 }
469 }
470
471 // set the frame title indicating the current number of threads
472 void MyFrame::OnIdle(wxIdleEvent &event)
473 {
474 // update the counts of running/total threads
475 size_t nRunning = 0,
476 nCount = wxGetApp().m_threads.Count();
477 for ( size_t n = 0; n < nCount; n++ )
478 {
479 if ( wxGetApp().m_threads[n]->IsRunning() )
480 nRunning++;
481 }
482
483 if ( nCount != m_nCount || nRunning != m_nRunning )
484 {
485 m_nRunning = nRunning;
486 m_nCount = nCount;
487
488 wxLogStatus(this, "%u threads total, %u running.", nCount, nRunning);
489 }
490 //else: avoid flicker - don't print anything
491 }
492
493 void MyFrame::OnQuit(wxCommandEvent& WXUNUSED(event) )
494 {
495 size_t count = wxGetApp().m_threads.Count();
496 for ( size_t i = 0; i < count; i++ )
497 {
498 wxGetApp().m_threads[0]->Delete();
499 }
500
501 Close(TRUE);
502 }
503
504 void MyFrame::OnAbout(wxCommandEvent& WXUNUSED(event) )
505 {
506 wxMessageDialog dialog(this, "wxWindows multithreaded application sample\n"
507 "(c) 1998 Julian Smart, Guilhem Lavaux\n"
508 "(c) 1999 Vadim Zeitlin\n"
509 "(c) 2000 Robert Roebling",
510 "About wxThread sample",
511 wxOK | wxICON_INFORMATION);
512
513 dialog.ShowModal();
514 }
515
516 void MyFrame::OnClear(wxCommandEvent& WXUNUSED(event))
517 {
518 m_txtctrl->Clear();
519 }
520
521 void MyFrame::OnStartWorker(wxCommandEvent& WXUNUSED(event))
522 {
523 MyWorkerThread *thread = new MyWorkerThread(this);
524
525 if ( thread->Create() != wxTHREAD_NO_ERROR )
526 {
527 wxLogError("Can't create thread!");
528 }
529
530 thread->Run();
531 }
532
533 void MyFrame::OnWorkerEvent(wxCommandEvent& event)
534 {
535 WriteText( "Got message from worker thread: " );
536 WriteText( event.GetString() );
537 WriteText( "\n" );
538 }
539