]> git.saurik.com Git - wxWidgets.git/blame_incremental - samples/thread/thread.cpp
Added wxStringBufferLength: works like wxStringBuffer, except
[wxWidgets.git] / samples / thread / thread.cpp
... / ...
CommitLineData
1/////////////////////////////////////////////////////////////////////////////
2// Name: thread.cpp
3// Purpose: wxWindows thread sample
4// Author: Guilhem Lavaux, Vadim Zeitlin
5// Modified by:
6// Created: 06/16/98
7// RCS-ID: $Id$
8// Copyright: (c) 1998-2002 wxWindows team
9// Licence: wxWindows license
10/////////////////////////////////////////////////////////////////////////////
11
12// For compilers that support precompilation, includes "wx/wx.h".
13#include "wx/wxprec.h"
14
15#ifdef __BORLANDC__
16 #pragma hdrstop
17#endif
18
19#ifndef WX_PRECOMP
20 #include "wx/wx.h"
21#endif
22
23#if !wxUSE_THREADS
24 #error "This sample requires thread support!"
25#endif // wxUSE_THREADS
26
27#include "wx/thread.h"
28#include "wx/dynarray.h"
29
30#include "wx/progdlg.h"
31
32// define this to use wxExecute in the exec tests, otherwise just use system
33#define USE_EXECUTE
34
35#ifdef USE_EXECUTE
36 #define EXEC(cmd) wxExecute((cmd), wxEXEC_SYNC)
37#else
38 #define EXEC(cmd) system(cmd)
39#endif
40
41class MyThread;
42WX_DEFINE_ARRAY(wxThread *, wxArrayThread);
43
44// Define a new application type
45class MyApp : public wxApp
46{
47public:
48 MyApp();
49 virtual ~MyApp();
50
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;
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;
69};
70
71// Create a new application object
72IMPLEMENT_APP(MyApp)
73
74// Define a new frame type
75class MyFrame: public wxFrame
76{
77public:
78 // ctor
79 MyFrame(wxFrame *frame, const wxString& title, int x, int y, int w, int h);
80
81 // operations
82 void WriteText(const wxString& text) { m_txtctrl->WriteText(text); }
83
84 // accessors for MyWorkerThread (called in its context!)
85 bool Cancelled();
86
87protected:
88 // callbacks
89 void OnQuit(wxCommandEvent& event);
90 void OnClear(wxCommandEvent& event);
91
92 void OnStartThread(wxCommandEvent& event);
93 void OnStartThreads(wxCommandEvent& event);
94 void OnStopThread(wxCommandEvent& event);
95 void OnPauseThread(wxCommandEvent& event);
96 void OnResumeThread(wxCommandEvent& event);
97
98 void OnStartWorker(wxCommandEvent& event);
99 void OnWorkerEvent(wxCommandEvent& event);
100 void OnUpdateWorker(wxUpdateUIEvent& event);
101
102 void OnExecMain(wxCommandEvent& event);
103 void OnExecThread(wxCommandEvent& event);
104
105 void OnShowCPUs(wxCommandEvent& event);
106 void OnAbout(wxCommandEvent& event);
107
108 void OnIdle(wxIdleEvent &event);
109
110private:
111 // helper function - creates a new thread (but doesn't run it)
112 MyThread *CreateThread();
113
114 // just some place to put our messages in
115 wxTextCtrl *m_txtctrl;
116
117 // remember the number of running threads and total number of threads
118 size_t m_nRunning, m_nCount;
119
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
129 DECLARE_EVENT_TABLE()
130};
131
132// ID for the menu commands
133enum
134{
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
151 WORKER_EVENT // this one gets sent from the worker thread
152};
153
154// ----------------------------------------------------------------------------
155// GUI thread
156// ----------------------------------------------------------------------------
157
158class MyThread : public wxThread
159{
160public:
161 MyThread(MyFrame *frame);
162
163 // thread execution starts here
164 virtual void *Entry();
165
166 // called when the thread exits - whether it terminates normally or is
167 // stopped with Delete() (but not when it is Kill()ed!)
168 virtual void OnExit();
169
170 // write something to the text control
171 void WriteText(const wxString& text);
172
173public:
174 size_t m_count;
175 MyFrame *m_frame;
176};
177
178MyThread::MyThread(MyFrame *frame)
179 : wxThread()
180{
181 m_count = 0;
182 m_frame = frame;
183}
184
185void MyThread::WriteText(const wxString& text)
186{
187 wxString msg;
188
189 // before doing any GUI calls we must ensure that this thread is the only
190 // one doing it!
191
192 wxMutexGuiEnter();
193
194 msg << text;
195 m_frame->WriteText(msg);
196
197 wxMutexGuiLeave();
198}
199
200void MyThread::OnExit()
201{
202 wxCriticalSectionLocker locker(wxGetApp().m_critsect);
203
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 }
219}
220
221void *MyThread::Entry()
222{
223 wxString text;
224
225 text.Printf(wxT("Thread 0x%lx started (priority = %u).\n"),
226 GetId(), GetPriority());
227 WriteText(text);
228 // wxLogMessage(text); -- test wxLog thread safeness
229
230 for ( m_count = 0; m_count < 10; m_count++ )
231 {
232 // check if we were asked to exit
233 if ( TestDestroy() )
234 break;
235
236 text.Printf(wxT("[%u] Thread 0x%lx here.\n"), m_count, GetId());
237 WriteText(text);
238
239 // wxSleep() can't be called from non-GUI thread!
240 wxThread::Sleep(1000);
241 }
242
243 text.Printf(wxT("Thread 0x%lx finished.\n"), GetId());
244 WriteText(text);
245 // wxLogMessage(text); -- test wxLog thread safeness
246
247 return NULL;
248}
249
250// ----------------------------------------------------------------------------
251// worker thread
252// ----------------------------------------------------------------------------
253
254class MyWorkerThread : public wxThread
255{
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;
269};
270
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{
284 for ( m_count = 0; !m_frame->Cancelled() && (m_count < 100); m_count++ )
285 {
286 // check if we were asked to exit
287 if ( TestDestroy() )
288 break;
289
290 // create any type of command event here
291 wxCommandEvent event( wxEVT_COMMAND_MENU_SELECTED, WORKER_EVENT );
292 event.SetInt( m_count );
293
294 // send in a thread-safe way
295 wxPostEvent( m_frame, event );
296
297 // wxSleep() can't be called from non-main thread!
298 wxThread::Sleep(200);
299 }
300
301 wxCommandEvent event( wxEVT_COMMAND_MENU_SELECTED, WORKER_EVENT );
302 event.SetInt(-1); // that's all
303 wxPostEvent( m_frame, event );
304
305 return NULL;
306}
307
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// ----------------------------------------------------------------------------
333
334BEGIN_EVENT_TABLE(MyFrame, wxFrame)
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)
351 EVT_MENU(WORKER_EVENT, MyFrame::OnWorkerEvent)
352
353 EVT_IDLE(MyFrame::OnIdle)
354END_EVENT_TABLE()
355
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
372// `Main program' equivalent, creating windows and returning main app frame
373bool MyApp::OnInit()
374{
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");
378
379 // Create the main frame window
380 MyFrame *frame = new MyFrame((wxFrame *)NULL, _T("wxWindows threads sample"),
381 50, 50, 450, 340);
382
383 // Make a menubar
384 wxMenuBar *menuBar = new wxMenuBar;
385
386 wxMenu *menuFile = new wxMenu;
387 menuFile->Append(THREAD_CLEAR, _T("&Clear log\tCtrl-L"));
388 menuFile->AppendSeparator();
389 menuFile->Append(THREAD_QUIT, _T("E&xit\tAlt-X"));
390 menuBar->Append(menuFile, _T("&File"));
391
392 wxMenu *menuThread = new wxMenu;
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"));
396 menuThread->AppendSeparator();
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"));
399 menuThread->AppendSeparator();
400 menuThread->Append(THREAD_START_WORKER, _T("Start &worker thread\tCtrl-W"));
401 menuBar->Append(menuThread, _T("&Thread"));
402
403 wxMenu *menuExec = new wxMenu;
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"));
407
408 wxMenu *menuHelp = new wxMenu;
409 menuHelp->Append(THREAD_SHOWCPUS, _T("&Show CPU count"));
410 menuHelp->AppendSeparator();
411 menuHelp->Append(THREAD_ABOUT, _T("&About..."));
412 menuBar->Append(menuHelp, _T("&Help"));
413
414 frame->SetMenuBar(menuBar);
415
416 // Show the frame
417 frame->Show(TRUE);
418
419 SetTopWindow(frame);
420
421 return TRUE;
422}
423
424// My frame constructor
425MyFrame::MyFrame(wxFrame *frame, const wxString& title,
426 int x, int y, int w, int h)
427 : wxFrame(frame, -1, title, wxPoint(x, y), wxSize(w, h))
428{
429 m_nRunning = m_nCount = 0;
430
431 m_dlgProgress = (wxProgressDialog *)NULL;
432
433 CreateStatusBar(2);
434
435 m_txtctrl = new wxTextCtrl(this, -1, _T(""), wxPoint(0, 0), wxSize(0, 0),
436 wxTE_MULTILINE | wxTE_READONLY);
437
438}
439
440MyThread *MyFrame::CreateThread()
441{
442 MyThread *thread = new MyThread(this);
443
444 if ( thread->Create() != wxTHREAD_NO_ERROR )
445 {
446 wxLogError(wxT("Can't create thread!"));
447 }
448
449 wxCriticalSectionLocker enter(wxGetApp().m_critsect);
450 wxGetApp().m_threads.Add(thread);
451
452 return thread;
453}
454
455void MyFrame::OnStartThreads(wxCommandEvent& WXUNUSED(event) )
456{
457 static long s_num = 10;
458
459 s_num = wxGetNumberFromUser(_T("How many threads to start: "), _T(""),
460 _T("wxThread sample"), s_num, 1, 10000, this);
461 if ( s_num == -1 )
462 {
463 s_num = 10;
464
465 return;
466 }
467
468 size_t count = (size_t)s_num, n;
469
470 wxArrayThread threads;
471
472 // first create them all...
473 for ( n = 0; n < count; n++ )
474 {
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);
488 }
489
490 wxString msg;
491 msg.Printf(wxT("%d new threads created."), count);
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
505 if ( thread->Run() != wxTHREAD_NO_ERROR )
506 {
507 wxLogError(wxT("Can't start thread!"));
508 }
509
510 SetStatusText(_T("New thread started."), 1);
511}
512
513void MyFrame::OnStopThread(wxCommandEvent& WXUNUSED(event) )
514{
515 wxGetApp().m_critsect.Enter();
516
517 // stop the last thread
518 if ( wxGetApp().m_threads.IsEmpty() )
519 {
520 wxLogError(wxT("No thread to stop!"));
521
522 wxGetApp().m_critsect.Leave();
523 }
524 else
525 {
526 wxThread *thread = wxGetApp().m_threads.Last();
527
528 // it's important to leave critical section before calling Delete()
529 // because delete will (implicitly) call OnExit() which also tries
530 // to enter the same crit section - would dead lock.
531 wxGetApp().m_critsect.Leave();
532
533 thread->Delete();
534
535 SetStatusText(_T("Thread stopped."), 1);
536 }
537}
538
539void MyFrame::OnResumeThread(wxCommandEvent& WXUNUSED(event) )
540{
541 wxCriticalSectionLocker enter(wxGetApp().m_critsect);
542
543 // resume first suspended thread
544 size_t n = 0, count = wxGetApp().m_threads.Count();
545 while ( n < count && !wxGetApp().m_threads[n]->IsPaused() )
546 n++;
547
548 if ( n == count )
549 {
550 wxLogError(wxT("No thread to resume!"));
551 }
552 else
553 {
554 wxGetApp().m_threads[n]->Resume();
555
556 SetStatusText(_T("Thread resumed."), 1);
557 }
558}
559
560void MyFrame::OnPauseThread(wxCommandEvent& WXUNUSED(event) )
561{
562 wxCriticalSectionLocker enter(wxGetApp().m_critsect);
563
564 // pause last running thread
565 int n = wxGetApp().m_threads.Count() - 1;
566 while ( n >= 0 && !wxGetApp().m_threads[n]->IsRunning() )
567 n--;
568
569 if ( n < 0 )
570 {
571 wxLogError(wxT("No thread to pause!"));
572 }
573 else
574 {
575 wxGetApp().m_threads[n]->Pause();
576
577 SetStatusText(_T("Thread paused."), 1);
578 }
579}
580
581// set the frame title indicating the current number of threads
582void MyFrame::OnIdle(wxIdleEvent& event)
583{
584 wxCriticalSectionLocker enter(wxGetApp().m_critsect);
585
586 // update the counts of running/total threads
587 size_t nRunning = 0,
588 nCount = wxGetApp().m_threads.Count();
589 for ( size_t n = 0; n < nCount; n++ )
590 {
591 if ( wxGetApp().m_threads[n]->IsRunning() )
592 nRunning++;
593 }
594
595 if ( nCount != m_nCount || nRunning != m_nRunning )
596 {
597 m_nRunning = nRunning;
598 m_nCount = nCount;
599
600 wxLogStatus(this, wxT("%u threads total, %u running."), nCount, nRunning);
601 }
602 //else: avoid flicker - don't print anything
603
604 event.Skip();
605}
606
607void MyFrame::OnQuit(wxCommandEvent& WXUNUSED(event) )
608{
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
616 {
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
648 }
649
650 Close(TRUE);
651}
652
653void MyFrame::OnExecMain(wxCommandEvent& WXUNUSED(event))
654{
655 wxLogMessage(wxT("The exit code from the main program is %ld"),
656 EXEC(_T("/bin/echo \"main program\"")));
657}
658
659void MyFrame::OnExecThread(wxCommandEvent& WXUNUSED(event))
660{
661 MyExecThread thread(wxT("/bin/echo \"child thread\""));
662 thread.Run();
663
664 wxLogMessage(wxT("The exit code from a child thread is %ld"),
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:
676 msg = _T("Unknown number of CPUs");
677 break;
678
679 case 0:
680 msg = _T("WARNING: you're running without any CPUs!");
681 break;
682
683 case 1:
684 msg = _T("This system only has one CPU.");
685 break;
686
687 default:
688 msg.Printf(wxT("This system has %d CPUs"), nCPUs);
689 }
690
691 wxLogMessage(msg);
692}
693
694void MyFrame::OnAbout(wxCommandEvent& WXUNUSED(event) )
695{
696 wxMessageDialog dialog(this,
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"),
702 wxOK | wxICON_INFORMATION);
703
704 dialog.ShowModal();
705}
706
707void MyFrame::OnClear(wxCommandEvent& WXUNUSED(event))
708{
709 m_txtctrl->Clear();
710}
711
712void MyFrame::OnUpdateWorker(wxUpdateUIEvent& event)
713{
714 event.Enable( m_dlgProgress == NULL );
715}
716
717void MyFrame::OnStartWorker(wxCommandEvent& WXUNUSED(event))
718{
719 MyWorkerThread *thread = new MyWorkerThread(this);
720
721 if ( thread->Create() != wxTHREAD_NO_ERROR )
722 {
723 wxLogError(wxT("Can't create thread!"));
724 }
725
726 m_dlgProgress = new wxProgressDialog
727 (
728 _T("Progress dialog"),
729 _T("Wait until the thread terminates or press [Cancel]"),
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
742 thread->Run();
743}
744
745void MyFrame::OnWorkerEvent(wxCommandEvent& event)
746{
747#if 0
748 WriteText( _T("Got message from worker thread: ") );
749 WriteText( event.GetString() );
750 WriteText( _T("\n") );
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
773}
774
775bool MyFrame::Cancelled()
776{
777 wxCriticalSectionLocker lock(m_critsectWork);
778
779 return m_cancelled;
780}