]> git.saurik.com Git - wxWidgets.git/blob - samples/thread/test.cpp
Removed lots of OnClose functions; doc'ed OnCloseWindow better;
[wxWidgets.git] / samples / thread / test.cpp
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
9 // Licence: wxWindows license
10 /////////////////////////////////////////////////////////////////////////////
11
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
20 #ifdef __GNUG__
21 #pragma implementation "test.cpp"
22 #pragma interface "test.cpp"
23 #endif
24
25 // For compilers that support precompilation, includes "wx/wx.h".
26 #include "wx/wxprec.h"
27
28 #ifdef __BORLANDC__
29 #pragma hdrstop
30 #endif
31
32 #ifndef WX_PRECOMP
33 #include "wx/wx.h"
34 #endif
35
36 #if !wxUSE_THREADS
37 #error "This sample requires thread support!"
38 #endif // wxUSE_THREADS
39
40 #include "wx/thread.h"
41 #include "wx/dynarray.h"
42 #include "wx/time.h"
43
44 // Define a new application type
45 class MyApp : public wxApp
46 {
47 public:
48 bool OnInit();
49 };
50
51 class MyThread;
52 WX_DEFINE_ARRAY(wxThread *, wxArrayThread);
53
54 // Define a new frame type
55 class MyFrame: public wxFrame
56 {
57 public:
58 // ctor
59 MyFrame(wxFrame *frame, const wxString& title, int x, int y, int w, int h);
60
61 // operations
62 void WriteText(const wxString& text) { m_txtctrl->WriteText(text); }
63
64 // callbacks
65 void OnQuit(wxCommandEvent& event);
66 void OnAbout(wxCommandEvent& event);
67 void OnClear(wxCommandEvent& event);
68
69 void OnStartThread(wxCommandEvent& event);
70 void OnStartThreads(wxCommandEvent& event);
71 void OnStopThread(wxCommandEvent& event);
72 void OnPauseThread(wxCommandEvent& event);
73 void OnResumeThread(wxCommandEvent& event);
74
75 void OnIdle(wxIdleEvent &event);
76
77 // called by dying thread _in_that_thread_context_
78 void OnThreadExit(wxThread *thread);
79
80 private:
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
85 wxCriticalSection m_critsect;
86
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
94 // the array of threads which finished (either because they did their work
95 // or because they were explicitly stopped)
96 wxArrayThread m_terminated;
97
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
103 // just some place to put our messages in
104 wxTextCtrl *m_txtctrl;
105
106 // remember the number of running threads and total number of threads
107 size_t m_nRunning, m_nCount;
108
109 DECLARE_EVENT_TABLE()
110 };
111
112 class MyThread : public wxThread
113 {
114 public:
115 MyThread(MyFrame *frame);
116
117 // thread execution starts here
118 virtual void *Entry();
119
120 // called when the thread exits - whether it terminates normally or is
121 // stopped with Delete() (but not when it is Kill()ed!)
122 virtual void OnExit();
123
124 // write something to the text control
125 void WriteText(const wxString& text);
126
127 public:
128 size_t m_count;
129 MyFrame *m_frame;
130 };
131
132 MyThread::MyThread(MyFrame *frame)
133 : wxThread()
134 {
135 m_count = 0;
136 m_frame = frame;
137 }
138
139 void MyThread::WriteText(const wxString& text)
140 {
141 wxString msg;
142 msg << wxTime().FormatTime() << ": " << text;
143
144 // before doing any GUI calls we must ensure that this thread is the only
145 // one doing it!
146 wxMutexGuiLocker guiLocker;
147
148 m_frame->WriteText(msg);
149 }
150
151 void MyThread::OnExit()
152 {
153 m_frame->OnThreadExit(this);
154 }
155
156 void *MyThread::Entry()
157 {
158 wxString text;
159
160 text.Printf("Thread 0x%x started.\n", GetID());
161 WriteText(text);
162
163 for ( m_count = 0; m_count < 10; m_count++ )
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);
171
172 // wxSleep() can't be called from non-GUI thread!
173 wxThread::Sleep(1000);
174 }
175
176 text.Printf("Thread 0x%x finished.\n", GetID());
177 WriteText(text);
178
179 return NULL;
180 }
181
182 // ID for the menu commands
183 enum
184 {
185 TEST_QUIT = 1,
186 TEST_TEXT = 101,
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
194 };
195
196 BEGIN_EVENT_TABLE(MyFrame, wxFrame)
197 EVT_MENU(TEST_QUIT, MyFrame::OnQuit)
198 EVT_MENU(TEST_ABOUT, MyFrame::OnAbout)
199 EVT_MENU(TEST_CLEAR, MyFrame::OnClear)
200 EVT_MENU(TEST_START_THREAD, MyFrame::OnStartThread)
201 EVT_MENU(TEST_START_THREADS, MyFrame::OnStartThreads)
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
206 EVT_IDLE(MyFrame::OnIdle)
207 END_EVENT_TABLE()
208
209 // Create a new application object
210 IMPLEMENT_APP (MyApp)
211
212 // `Main program' equivalent, creating windows and returning main app frame
213 bool MyApp::OnInit()
214 {
215 // Create the main frame window
216 MyFrame *frame = new MyFrame((wxFrame *)NULL, "wxWindows threads sample",
217 50, 50, 450, 340);
218
219 // Make a menubar
220 wxMenu *file_menu = new wxMenu;
221
222 file_menu->Append(TEST_CLEAR, "&Clear log");
223 file_menu->AppendSeparator();
224 file_menu->Append(TEST_ABOUT, "&About");
225 file_menu->AppendSeparator();
226 file_menu->Append(TEST_QUIT, "E&xit");
227 wxMenuBar *menu_bar = new wxMenuBar;
228 menu_bar->Append(file_menu, "&File");
229
230 wxMenu *thread_menu = new wxMenu;
231 thread_menu->Append(TEST_START_THREAD, "&Start a new thread");
232 thread_menu->Append(TEST_START_THREADS, "Start &many threads at once");
233 thread_menu->Append(TEST_STOP_THREAD, "S&top a running thread");
234 thread_menu->AppendSeparator();
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");
238 frame->SetMenuBar(menu_bar);
239
240 // Show the frame
241 frame->Show(TRUE);
242
243 SetTopWindow(frame);
244
245 return TRUE;
246 }
247
248 // My frame constructor
249 MyFrame::MyFrame(wxFrame *frame, const wxString& title,
250 int x, int y, int w, int h)
251 : wxFrame(frame, -1, title, wxPoint(x, y), wxSize(w, h))
252 {
253 m_nRunning = m_nCount = 0;
254
255 CreateStatusBar(2);
256
257 m_txtctrl = new wxTextCtrl(this, -1, "", wxPoint(0, 0), wxSize(0, 0),
258 wxTE_MULTILINE | wxTE_READONLY);
259
260 }
261
262 MyThread *MyFrame::CreateThread()
263 {
264 MyThread *thread = new MyThread(this);
265
266 if ( thread->Create() != wxTHREAD_NO_ERROR )
267 {
268 wxLogError("Can't create thread!");
269 }
270
271 wxCriticalSectionLocker enter(m_critsect);
272 m_threads.Add(thread);
273
274 return thread;
275 }
276
277 void 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
310 void MyFrame::OnStartThread(wxCommandEvent& WXUNUSED(event) )
311 {
312 MyThread *thread = CreateThread();
313
314 if ( thread->Run() != wxTHREAD_NO_ERROR )
315 {
316 wxLogError("Can't start thread!");
317 }
318
319 SetStatusText("New thread started.", 1);
320 }
321
322 void MyFrame::OnStopThread(wxCommandEvent& WXUNUSED(event) )
323 {
324 // stop the last thread
325 if ( m_threads.IsEmpty() )
326 {
327 wxLogError("No thread to stop!");
328 }
329 else
330 {
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);
344 }
345 }
346
347 void MyFrame::OnResumeThread(wxCommandEvent& WXUNUSED(event) )
348 {
349 wxCriticalSectionLocker enter(m_critsect);
350
351 // resume first suspended thread
352 size_t n = 0, count = m_threads.Count();
353 while ( n < count && !m_threads[n]->IsPaused() )
354 n++;
355
356 if ( n == count )
357 {
358 wxLogError("No thread to resume!");
359 }
360 else
361 {
362 m_threads[n]->Resume();
363
364 SetStatusText("Thread resumed.", 1);
365 }
366 }
367
368 void MyFrame::OnPauseThread(wxCommandEvent& WXUNUSED(event) )
369 {
370 wxCriticalSectionLocker enter(m_critsect);
371
372 // pause last running thread
373 int n = m_threads.Count() - 1;
374 while ( n >= 0 && !m_threads[n]->IsRunning() )
375 n--;
376
377 if ( n < 0 )
378 {
379 wxLogError("No thread to pause!");
380 }
381 else
382 {
383 m_threads[n]->Pause();
384
385 SetStatusText("Thread paused.", 1);
386 }
387 }
388
389 // set the frame title indicating the current number of threads
390 void MyFrame::OnIdle(wxIdleEvent &event)
391 {
392 // first wait for all the threads which dies since the last call
393 {
394 wxCriticalSectionLocker enter(m_critsect);
395
396 size_t nCount = m_terminated.GetCount();
397 for ( size_t n = 0; n < nCount; n++ )
398 {
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();
404 }
405
406 m_stopped.Empty();
407 m_terminated.Empty();
408 }
409
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
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
426 }
427
428 void MyFrame::OnQuit(wxCommandEvent& WXUNUSED(event) )
429 {
430 size_t count = m_threads.Count();
431 for ( size_t i = 0; i < count; i++ )
432 {
433 m_threads[i]->Delete();
434 }
435
436 Close(TRUE);
437 }
438
439 void MyFrame::OnAbout(wxCommandEvent& WXUNUSED(event) )
440 {
441 wxMessageDialog dialog(this, "wxWindows multithreaded application sample\n"
442 "(c) 1998 Julian Smart, Guilhem Lavaux\n"
443 "(c) 1999 Vadim Zeitlin",
444 "About wxThread sample",
445 wxOK | wxICON_INFORMATION);
446
447 dialog.ShowModal();
448 }
449
450 void MyFrame::OnClear(wxCommandEvent& WXUNUSED(event))
451 {
452 m_txtctrl->Clear();
453 }
454
455 void MyFrame::OnThreadExit(wxThread *thread)
456 {
457 wxCriticalSectionLocker enter(m_critsect);
458
459 m_threads.Remove(thread);
460 m_terminated.Add(thread);
461 }