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