]> git.saurik.com Git - wxWidgets.git/blame - samples/thread/test.cpp
code demonstrating wxMSW bug added
[wxWidgets.git] / samples / thread / test.cpp
CommitLineData
82052aff
GL
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
3222fde2 9// Licence: wxWindows license
82052aff
GL
10/////////////////////////////////////////////////////////////////////////////
11
bee503b0
VZ
12/*
13 TODO:
14
15 1. show how SetPriority() works.
16 2. use worker threads to update progress controls instead of writing
17 messages - it will be more visual
18 */
19
82052aff 20#ifdef __GNUG__
bee503b0
VZ
21 #pragma implementation "test.cpp"
22 #pragma interface "test.cpp"
82052aff
GL
23#endif
24
25// For compilers that support precompilation, includes "wx/wx.h".
26#include "wx/wxprec.h"
27
28#ifdef __BORLANDC__
3222fde2 29 #pragma hdrstop
82052aff
GL
30#endif
31
32#ifndef WX_PRECOMP
3222fde2 33 #include "wx/wx.h"
82052aff
GL
34#endif
35
3222fde2
VZ
36#if !wxUSE_THREADS
37 #error "This sample requires thread support!"
38#endif // wxUSE_THREADS
39
82052aff
GL
40#include "wx/thread.h"
41#include "wx/dynarray.h"
3222fde2 42#include "wx/time.h"
82052aff
GL
43
44// Define a new application type
bf1852e1 45class MyApp : public wxApp
82052aff 46{
a6b0bd49 47public:
bf1852e1 48 bool OnInit();
82052aff
GL
49};
50
7c3d7e2d 51class MyThread;
a6b0bd49 52WX_DEFINE_ARRAY(wxThread *, wxArrayThread);
82052aff
GL
53
54// Define a new frame type
55class MyFrame: public wxFrame
56{
a6b0bd49
VZ
57public:
58 // ctor
bf1852e1 59 MyFrame(wxFrame *frame, const wxString& title, int x, int y, int w, int h);
3222fde2 60
a6b0bd49
VZ
61 // operations
62 void WriteText(const wxString& text) { m_txtctrl->WriteText(text); }
63
64 // callbacks
82052aff
GL
65 void OnQuit(wxCommandEvent& event);
66 void OnAbout(wxCommandEvent& event);
bee503b0 67 void OnClear(wxCommandEvent& event);
a6b0bd49 68
82052aff 69 void OnStartThread(wxCommandEvent& event);
7c3d7e2d 70 void OnStartThreads(wxCommandEvent& event);
82052aff
GL
71 void OnStopThread(wxCommandEvent& event);
72 void OnPauseThread(wxCommandEvent& event);
a6b0bd49
VZ
73 void OnResumeThread(wxCommandEvent& event);
74
3222fde2 75 void OnIdle(wxIdleEvent &event);
3222fde2 76
7c3d7e2d 77 // called by dying thread _in_that_thread_context_
bee503b0
VZ
78 void OnThreadExit(wxThread *thread);
79
a6b0bd49 80private:
7c3d7e2d
VZ
81 // helper function - creates a new thread (but doesn't run it)
82 MyThread *CreateThread();
83
84 // crit section protects access to all of the arrays below
bee503b0 85 wxCriticalSection m_critsect;
bee503b0 86
7c3d7e2d
VZ
87 // all the threads currently alive - as soon as the thread terminates, it's
88 // removed from the array
89 wxArrayThread m_threads;
90
91 // both of these arrays are only valid between 2 iterations of OnIdle(),
92 // they're cleared each time it is excuted.
93
bf1852e1
VZ
94 // the array of threads which finished (either because they did their work
95 // or because they were explicitly stopped)
7c3d7e2d 96 wxArrayThread m_terminated;
bf1852e1 97
7c3d7e2d
VZ
98 // the array of threads which were stopped by the user and not terminated
99 // by themselves - these threads shouldn't be Delete()d second time from
100 // OnIdle()
101 wxArrayThread m_stopped;
102
bf1852e1
VZ
103 // just some place to put our messages in
104 wxTextCtrl *m_txtctrl;
3222fde2 105
7c3d7e2d
VZ
106 // remember the number of running threads and total number of threads
107 size_t m_nRunning, m_nCount;
108
a6b0bd49 109 DECLARE_EVENT_TABLE()
82052aff
GL
110};
111
bee503b0 112class MyThread : public wxThread
82052aff 113{
a6b0bd49 114public:
82052aff 115 MyThread(MyFrame *frame);
3222fde2
VZ
116
117 // thread execution starts here
118 virtual void *Entry();
119
bf1852e1
VZ
120 // called when the thread exits - whether it terminates normally or is
121 // stopped with Delete() (but not when it is Kill()ed!)
bee503b0
VZ
122 virtual void OnExit();
123
3222fde2
VZ
124 // write something to the text control
125 void WriteText(const wxString& text);
a6b0bd49
VZ
126
127public:
128 size_t m_count;
82052aff
GL
129 MyFrame *m_frame;
130};
131
132MyThread::MyThread(MyFrame *frame)
a6b0bd49 133 : wxThread()
82052aff 134{
a6b0bd49
VZ
135 m_count = 0;
136 m_frame = frame;
82052aff
GL
137}
138
3222fde2
VZ
139void MyThread::WriteText(const wxString& text)
140{
141 wxString msg;
3222fde2
VZ
142
143 // before doing any GUI calls we must ensure that this thread is the only
144 // one doing it!
bee503b0 145 wxMutexGuiLocker guiLocker;
81f1bb40 146 msg << wxTime().FormatTime() << ": " << text;
bee503b0 147
3222fde2 148 m_frame->WriteText(msg);
bee503b0
VZ
149}
150
151void MyThread::OnExit()
152{
153 m_frame->OnThreadExit(this);
3222fde2
VZ
154}
155
82052aff
GL
156void *MyThread::Entry()
157{
a6b0bd49 158 wxString text;
3222fde2 159
3222fde2
VZ
160 text.Printf("Thread 0x%x started.\n", GetID());
161 WriteText(text);
162
bee503b0 163 for ( m_count = 0; m_count < 10; m_count++ )
3222fde2
VZ
164 {
165 // check if we were asked to exit
166 if ( TestDestroy() )
167 break;
168
169 text.Printf("[%u] Thread 0x%x here.\n", m_count, GetID());
170 WriteText(text);
a6b0bd49 171
bf1852e1
VZ
172 // wxSleep() can't be called from non-GUI thread!
173 wxThread::Sleep(1000);
a6b0bd49 174 }
3222fde2
VZ
175
176 text.Printf("Thread 0x%x finished.\n", GetID());
177 WriteText(text);
178
a6b0bd49 179 return NULL;
82052aff
GL
180}
181
182// ID for the menu commands
3222fde2
VZ
183enum
184{
185 TEST_QUIT = 1,
186 TEST_TEXT = 101,
7c3d7e2d
VZ
187 TEST_ABOUT,
188 TEST_CLEAR,
189 TEST_START_THREAD = 201,
190 TEST_START_THREADS,
191 TEST_STOP_THREAD,
192 TEST_PAUSE_THREAD,
193 TEST_RESUME_THREAD
3222fde2 194};
82052aff
GL
195
196BEGIN_EVENT_TABLE(MyFrame, wxFrame)
a6b0bd49
VZ
197 EVT_MENU(TEST_QUIT, MyFrame::OnQuit)
198 EVT_MENU(TEST_ABOUT, MyFrame::OnAbout)
bee503b0 199 EVT_MENU(TEST_CLEAR, MyFrame::OnClear)
a6b0bd49 200 EVT_MENU(TEST_START_THREAD, MyFrame::OnStartThread)
7c3d7e2d 201 EVT_MENU(TEST_START_THREADS, MyFrame::OnStartThreads)
a6b0bd49
VZ
202 EVT_MENU(TEST_STOP_THREAD, MyFrame::OnStopThread)
203 EVT_MENU(TEST_PAUSE_THREAD, MyFrame::OnPauseThread)
204 EVT_MENU(TEST_RESUME_THREAD, MyFrame::OnResumeThread)
205
3222fde2 206 EVT_IDLE(MyFrame::OnIdle)
82052aff
GL
207END_EVENT_TABLE()
208
209// Create a new application object
3222fde2 210IMPLEMENT_APP (MyApp)
82052aff
GL
211
212// `Main program' equivalent, creating windows and returning main app frame
3222fde2 213bool MyApp::OnInit()
82052aff 214{
a6b0bd49 215 // Create the main frame window
bee503b0
VZ
216 MyFrame *frame = new MyFrame((wxFrame *)NULL, "wxWindows threads sample",
217 50, 50, 450, 340);
3222fde2 218
a6b0bd49
VZ
219 // Make a menubar
220 wxMenu *file_menu = new wxMenu;
3222fde2 221
bee503b0
VZ
222 file_menu->Append(TEST_CLEAR, "&Clear log");
223 file_menu->AppendSeparator();
a6b0bd49 224 file_menu->Append(TEST_ABOUT, "&About");
bee503b0 225 file_menu->AppendSeparator();
a6b0bd49
VZ
226 file_menu->Append(TEST_QUIT, "E&xit");
227 wxMenuBar *menu_bar = new wxMenuBar;
228 menu_bar->Append(file_menu, "&File");
3222fde2 229
a6b0bd49 230 wxMenu *thread_menu = new wxMenu;
3222fde2 231 thread_menu->Append(TEST_START_THREAD, "&Start a new thread");
7c3d7e2d 232 thread_menu->Append(TEST_START_THREADS, "Start &many threads at once");
3222fde2 233 thread_menu->Append(TEST_STOP_THREAD, "S&top a running thread");
a6b0bd49 234 thread_menu->AppendSeparator();
3222fde2
VZ
235 thread_menu->Append(TEST_PAUSE_THREAD, "&Pause a running thread");
236 thread_menu->Append(TEST_RESUME_THREAD, "&Resume suspended thread");
237 menu_bar->Append(thread_menu, "&Thread");
a6b0bd49 238 frame->SetMenuBar(menu_bar);
3222fde2 239
a6b0bd49
VZ
240 // Show the frame
241 frame->Show(TRUE);
3222fde2 242
a6b0bd49 243 SetTopWindow(frame);
3222fde2 244
a6b0bd49 245 return TRUE;
82052aff
GL
246}
247
248// My frame constructor
bf1852e1
VZ
249MyFrame::MyFrame(wxFrame *frame, const wxString& title,
250 int x, int y, int w, int h)
a6b0bd49 251 : wxFrame(frame, -1, title, wxPoint(x, y), wxSize(w, h))
82052aff 252{
7c3d7e2d
VZ
253 m_nRunning = m_nCount = 0;
254
255 CreateStatusBar(2);
3222fde2 256
bee503b0
VZ
257 m_txtctrl = new wxTextCtrl(this, -1, "", wxPoint(0, 0), wxSize(0, 0),
258 wxTE_MULTILINE | wxTE_READONLY);
82052aff 259
a6b0bd49 260}
82052aff 261
7c3d7e2d 262MyThread *MyFrame::CreateThread()
a6b0bd49
VZ
263{
264 MyThread *thread = new MyThread(this);
3222fde2 265
bf1852e1
VZ
266 if ( thread->Create() != wxTHREAD_NO_ERROR )
267 {
268 wxLogError("Can't create thread!");
269 }
3222fde2 270
bee503b0 271 wxCriticalSectionLocker enter(m_critsect);
a6b0bd49 272 m_threads.Add(thread);
bf1852e1 273
7c3d7e2d
VZ
274 return thread;
275}
276
277void MyFrame::OnStartThreads(wxCommandEvent& WXUNUSED(event) )
278{
279 static wxString s_str;
280 s_str = wxGetTextFromUser("How many threads to start: ",
281 "wxThread sample",
282 s_str, this);
283 if ( s_str.IsEmpty() )
284 return;
285
286 size_t count, n;
287 sscanf(s_str, "%u", &count);
288 if ( count == 0 )
289 return;
290
291 wxArrayThread threads;
292
293 // first create them all...
294 for ( n = 0; n < count; n++ )
295 {
296 threads.Add(CreateThread());
297 }
298
299 wxString msg;
300 msg.Printf("%d new threads created.", count);
301 SetStatusText(msg, 1);
302
303 // ...and then start them
304 for ( n = 0; n < count; n++ )
305 {
306 threads[n]->Run();
307 }
308}
309
310void MyFrame::OnStartThread(wxCommandEvent& WXUNUSED(event) )
311{
312 MyThread *thread = CreateThread();
313
bf1852e1
VZ
314 if ( thread->Run() != wxTHREAD_NO_ERROR )
315 {
316 wxLogError("Can't start thread!");
317 }
7c3d7e2d
VZ
318
319 SetStatusText("New thread started.", 1);
82052aff
GL
320}
321
e3e65dac 322void MyFrame::OnStopThread(wxCommandEvent& WXUNUSED(event) )
82052aff 323{
bf1852e1
VZ
324 // stop the last thread
325 if ( m_threads.IsEmpty() )
bee503b0
VZ
326 {
327 wxLogError("No thread to stop!");
bee503b0 328 }
bf1852e1
VZ
329 else
330 {
7c3d7e2d
VZ
331 m_critsect.Enter();
332
333 wxThread *thread = m_threads.Last();
334 m_stopped.Add(thread);
335
336 // it's important to leave critical section before calling Delete()
337 // because delete will (implicitly) call OnThreadExit() which also tries
338 // to enter the same crit section - would dead lock.
339 m_critsect.Leave();
340
341 thread->Delete();
342
343 SetStatusText("Thread stopped.", 1);
bf1852e1 344 }
a6b0bd49 345}
82052aff 346
a6b0bd49
VZ
347void MyFrame::OnResumeThread(wxCommandEvent& WXUNUSED(event) )
348{
bee503b0
VZ
349 wxCriticalSectionLocker enter(m_critsect);
350
3222fde2 351 // resume first suspended thread
bf1852e1
VZ
352 size_t n = 0, count = m_threads.Count();
353 while ( n < count && !m_threads[n]->IsPaused() )
354 n++;
3222fde2 355
bf1852e1 356 if ( n == count )
7c3d7e2d 357 {
bee503b0 358 wxLogError("No thread to resume!");
7c3d7e2d 359 }
a6b0bd49 360 else
7c3d7e2d 361 {
a6b0bd49 362 m_threads[n]->Resume();
7c3d7e2d
VZ
363
364 SetStatusText("Thread resumed.", 1);
365 }
82052aff
GL
366}
367
e3e65dac 368void MyFrame::OnPauseThread(wxCommandEvent& WXUNUSED(event) )
f3855ef0 369{
bee503b0
VZ
370 wxCriticalSectionLocker enter(m_critsect);
371
3222fde2 372 // pause last running thread
a6b0bd49
VZ
373 int n = m_threads.Count() - 1;
374 while ( n >= 0 && !m_threads[n]->IsRunning() )
375 n--;
3222fde2 376
a6b0bd49 377 if ( n < 0 )
7c3d7e2d 378 {
a6b0bd49 379 wxLogError("No thread to pause!");
7c3d7e2d 380 }
a6b0bd49 381 else
7c3d7e2d 382 {
a6b0bd49 383 m_threads[n]->Pause();
7c3d7e2d
VZ
384
385 SetStatusText("Thread paused.", 1);
386 }
f3855ef0
RR
387}
388
3222fde2
VZ
389// set the frame title indicating the current number of threads
390void MyFrame::OnIdle(wxIdleEvent &event)
391{
7c3d7e2d 392 // first wait for all the threads which dies since the last call
bee503b0
VZ
393 {
394 wxCriticalSectionLocker enter(m_critsect);
395
7c3d7e2d 396 size_t nCount = m_terminated.GetCount();
bee503b0 397 for ( size_t n = 0; n < nCount; n++ )
bf1852e1 398 {
7c3d7e2d
VZ
399 // don't delete the threads which were stopped - they were already
400 // deleted in OnStopThread()
401 wxThread *thread = m_terminated[n];
402 if ( m_stopped.Index(thread) == wxNOT_FOUND )
403 thread->Delete();
bf1852e1 404 }
bee503b0 405
7c3d7e2d
VZ
406 m_stopped.Empty();
407 m_terminated.Empty();
bee503b0
VZ
408 }
409
3222fde2
VZ
410 size_t nRunning = 0,
411 nCount = m_threads.Count();
412 for ( size_t n = 0; n < nCount; n++ )
413 {
414 if ( m_threads[n]->IsRunning() )
415 nRunning++;
416 }
417
7c3d7e2d
VZ
418 if ( nCount != m_nCount || nRunning != m_nRunning )
419 {
420 m_nRunning = nRunning;
421 m_nCount = nCount;
422
423 wxLogStatus(this, "%u threads total, %u running.", nCount, nRunning);
424 }
425 //else: avoid flicker - don't print anything
f3855ef0 426}
82052aff 427
e3e65dac 428void MyFrame::OnQuit(wxCommandEvent& WXUNUSED(event) )
82052aff 429{
bf1852e1
VZ
430 size_t count = m_threads.Count();
431 for ( size_t i = 0; i < count; i++ )
432 {
433 m_threads[i]->Delete();
434 }
3222fde2 435
a6b0bd49 436 Close(TRUE);
82052aff
GL
437}
438
e3e65dac 439void MyFrame::OnAbout(wxCommandEvent& WXUNUSED(event) )
82052aff 440{
bf1852e1
VZ
441 wxMessageDialog dialog(this, "wxWindows multithreaded application sample\n"
442 "(c) 1998 Julian Smart, Guilhem Lavaux\n"
443 "(c) 1999 Vadim Zeitlin",
3222fde2
VZ
444 "About wxThread sample",
445 wxOK | wxICON_INFORMATION);
446
a6b0bd49 447 dialog.ShowModal();
82052aff
GL
448}
449
bee503b0
VZ
450void MyFrame::OnClear(wxCommandEvent& WXUNUSED(event))
451{
452 m_txtctrl->Clear();
453}
454
455void MyFrame::OnThreadExit(wxThread *thread)
456{
bee503b0
VZ
457 wxCriticalSectionLocker enter(m_critsect);
458
7c3d7e2d
VZ
459 m_threads.Remove(thread);
460 m_terminated.Add(thread);
bee503b0 461}