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