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