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