]> git.saurik.com Git - wxWidgets.git/blob - samples/thread/test.cpp
wxThread POSIX implementation seems to work (under libc6 Linux at least)
[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 bool OnClose() { return TRUE; }
77
78 // called by dying thread _in_that_thread_context_
79 void OnThreadExit(wxThread *thread);
80
81 private:
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
86 wxCriticalSection m_critsect;
87
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
95 // the array of threads which finished (either because they did their work
96 // or because they were explicitly stopped)
97 wxArrayThread m_terminated;
98
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
104 // just some place to put our messages in
105 wxTextCtrl *m_txtctrl;
106
107 // remember the number of running threads and total number of threads
108 size_t m_nRunning, m_nCount;
109
110 DECLARE_EVENT_TABLE()
111 };
112
113 class MyThread : public wxThread
114 {
115 public:
116 MyThread(MyFrame *frame);
117
118 // thread execution starts here
119 virtual void *Entry();
120
121 // called when the thread exits - whether it terminates normally or is
122 // stopped with Delete() (but not when it is Kill()ed!)
123 virtual void OnExit();
124
125 // write something to the text control
126 void WriteText(const wxString& text);
127
128 public:
129 size_t m_count;
130 MyFrame *m_frame;
131 };
132
133 MyThread::MyThread(MyFrame *frame)
134 : wxThread()
135 {
136 m_count = 0;
137 m_frame = frame;
138 }
139
140 void 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!
147 wxMutexGuiLocker guiLocker;
148
149 m_frame->WriteText(msg);
150 }
151
152 void MyThread::OnExit()
153 {
154 m_frame->OnThreadExit(this);
155 }
156
157 void *MyThread::Entry()
158 {
159 wxString text;
160
161 text.Printf("Thread 0x%x started.\n", GetID());
162 WriteText(text);
163
164 for ( m_count = 0; m_count < 10; m_count++ )
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);
172
173 // wxSleep() can't be called from non-GUI thread!
174 wxThread::Sleep(1000);
175 }
176
177 text.Printf("Thread 0x%x finished.\n", GetID());
178 WriteText(text);
179
180 return NULL;
181 }
182
183 // ID for the menu commands
184 enum
185 {
186 TEST_QUIT = 1,
187 TEST_TEXT = 101,
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
195 };
196
197 BEGIN_EVENT_TABLE(MyFrame, wxFrame)
198 EVT_MENU(TEST_QUIT, MyFrame::OnQuit)
199 EVT_MENU(TEST_ABOUT, MyFrame::OnAbout)
200 EVT_MENU(TEST_CLEAR, MyFrame::OnClear)
201 EVT_MENU(TEST_START_THREAD, MyFrame::OnStartThread)
202 EVT_MENU(TEST_START_THREADS, MyFrame::OnStartThreads)
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
207 EVT_IDLE(MyFrame::OnIdle)
208 END_EVENT_TABLE()
209
210 // Create a new application object
211 IMPLEMENT_APP (MyApp)
212
213 // `Main program' equivalent, creating windows and returning main app frame
214 bool MyApp::OnInit()
215 {
216 // Create the main frame window
217 MyFrame *frame = new MyFrame((wxFrame *)NULL, "wxWindows threads sample",
218 50, 50, 450, 340);
219
220 // Make a menubar
221 wxMenu *file_menu = new wxMenu;
222
223 file_menu->Append(TEST_CLEAR, "&Clear log");
224 file_menu->AppendSeparator();
225 file_menu->Append(TEST_ABOUT, "&About");
226 file_menu->AppendSeparator();
227 file_menu->Append(TEST_QUIT, "E&xit");
228 wxMenuBar *menu_bar = new wxMenuBar;
229 menu_bar->Append(file_menu, "&File");
230
231 wxMenu *thread_menu = new wxMenu;
232 thread_menu->Append(TEST_START_THREAD, "&Start a new thread");
233 thread_menu->Append(TEST_START_THREADS, "Start &many threads at once");
234 thread_menu->Append(TEST_STOP_THREAD, "S&top a running thread");
235 thread_menu->AppendSeparator();
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");
239 frame->SetMenuBar(menu_bar);
240
241 // Show the frame
242 frame->Show(TRUE);
243
244 SetTopWindow(frame);
245
246 return TRUE;
247 }
248
249 // My frame constructor
250 MyFrame::MyFrame(wxFrame *frame, const wxString& title,
251 int x, int y, int w, int h)
252 : wxFrame(frame, -1, title, wxPoint(x, y), wxSize(w, h))
253 {
254 m_nRunning = m_nCount = 0;
255
256 CreateStatusBar(2);
257
258 m_txtctrl = new wxTextCtrl(this, -1, "", wxPoint(0, 0), wxSize(0, 0),
259 wxTE_MULTILINE | wxTE_READONLY);
260
261 }
262
263 MyThread *MyFrame::CreateThread()
264 {
265 MyThread *thread = new MyThread(this);
266
267 if ( thread->Create() != wxTHREAD_NO_ERROR )
268 {
269 wxLogError("Can't create thread!");
270 }
271
272 wxCriticalSectionLocker enter(m_critsect);
273 m_threads.Add(thread);
274
275 return thread;
276 }
277
278 void 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
311 void MyFrame::OnStartThread(wxCommandEvent& WXUNUSED(event) )
312 {
313 MyThread *thread = CreateThread();
314
315 if ( thread->Run() != wxTHREAD_NO_ERROR )
316 {
317 wxLogError("Can't start thread!");
318 }
319
320 SetStatusText("New thread started.", 1);
321 }
322
323 void MyFrame::OnStopThread(wxCommandEvent& WXUNUSED(event) )
324 {
325 // stop the last thread
326 if ( m_threads.IsEmpty() )
327 {
328 wxLogError("No thread to stop!");
329 }
330 else
331 {
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);
345 }
346 }
347
348 void MyFrame::OnResumeThread(wxCommandEvent& WXUNUSED(event) )
349 {
350 wxCriticalSectionLocker enter(m_critsect);
351
352 // resume first suspended thread
353 size_t n = 0, count = m_threads.Count();
354 while ( n < count && !m_threads[n]->IsPaused() )
355 n++;
356
357 if ( n == count )
358 {
359 wxLogError("No thread to resume!");
360 }
361 else
362 {
363 m_threads[n]->Resume();
364
365 SetStatusText("Thread resumed.", 1);
366 }
367 }
368
369 void MyFrame::OnPauseThread(wxCommandEvent& WXUNUSED(event) )
370 {
371 wxCriticalSectionLocker enter(m_critsect);
372
373 // pause last running thread
374 int n = m_threads.Count() - 1;
375 while ( n >= 0 && !m_threads[n]->IsRunning() )
376 n--;
377
378 if ( n < 0 )
379 {
380 wxLogError("No thread to pause!");
381 }
382 else
383 {
384 m_threads[n]->Pause();
385
386 SetStatusText("Thread paused.", 1);
387 }
388 }
389
390 // set the frame title indicating the current number of threads
391 void MyFrame::OnIdle(wxIdleEvent &event)
392 {
393 // first wait for all the threads which dies since the last call
394 {
395 wxCriticalSectionLocker enter(m_critsect);
396
397 size_t nCount = m_terminated.GetCount();
398 for ( size_t n = 0; n < nCount; n++ )
399 {
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();
405 }
406
407 m_stopped.Empty();
408 m_terminated.Empty();
409 }
410
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
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
427 }
428
429 void MyFrame::OnQuit(wxCommandEvent& WXUNUSED(event) )
430 {
431 size_t count = m_threads.Count();
432 for ( size_t i = 0; i < count; i++ )
433 {
434 m_threads[i]->Delete();
435 }
436
437 Close(TRUE);
438 }
439
440 void MyFrame::OnAbout(wxCommandEvent& WXUNUSED(event) )
441 {
442 wxMessageDialog dialog(this, "wxWindows multithreaded application sample\n"
443 "(c) 1998 Julian Smart, Guilhem Lavaux\n"
444 "(c) 1999 Vadim Zeitlin",
445 "About wxThread sample",
446 wxOK | wxICON_INFORMATION);
447
448 dialog.ShowModal();
449 }
450
451 void MyFrame::OnClear(wxCommandEvent& WXUNUSED(event))
452 {
453 m_txtctrl->Clear();
454 }
455
456 void MyFrame::OnThreadExit(wxThread *thread)
457 {
458 wxCriticalSectionLocker enter(m_critsect);
459
460 m_threads.Remove(thread);
461 m_terminated.Add(thread);
462 }