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