1 /////////////////////////////////////////////////////////////////////////////
3 // Purpose: wxWindows thread sample
4 // Author: Julian Smart(minimal)/Guilhem Lavaux(thread test)
8 // Copyright: (c) Julian Smart, Markus Holzem, Guilhem Lavaux
9 // Licence: wxWindows license
10 /////////////////////////////////////////////////////////////////////////////
13 TODO: use worker threads to update progress controls instead of writing
14 messages - it will be more visual
18 #pragma implementation "test.cpp"
19 #pragma interface "test.cpp"
22 // For compilers that support precompilation, includes "wx/wx.h".
23 #include "wx/wxprec.h"
34 #error "This sample requires thread support!"
35 #endif // wxUSE_THREADS
37 #include "wx/thread.h"
38 #include "wx/dynarray.h"
42 WX_DEFINE_ARRAY(wxThread
*, wxArrayThread
);
44 // Define a new application type
45 class MyApp
: public wxApp
48 virtual bool OnInit();
51 // all the threads currently alive - as soon as the thread terminates, it's
52 // removed from the array
53 wxArrayThread m_threads
;
55 // crit section protects access to all of the arrays below
56 wxCriticalSection m_critsect
;
59 // Create a new application object
62 // Define a new frame type
63 class MyFrame
: public wxFrame
67 MyFrame(wxFrame
*frame
, const wxString
& title
, int x
, int y
, int w
, int h
);
70 void WriteText(const wxString
& text
) { m_txtctrl
->WriteText(text
); }
73 void OnQuit(wxCommandEvent
& event
);
74 void OnAbout(wxCommandEvent
& event
);
75 void OnClear(wxCommandEvent
& event
);
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
);
83 void OnIdle(wxIdleEvent
&event
);
86 // helper function - creates a new thread (but doesn't run it)
87 MyThread
*CreateThread();
89 // just some place to put our messages in
90 wxTextCtrl
*m_txtctrl
;
92 // remember the number of running threads and total number of threads
93 size_t m_nRunning
, m_nCount
;
98 class MyThread
: public wxThread
101 MyThread(MyFrame
*frame
);
103 // thread execution starts here
104 virtual void *Entry();
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();
110 // write something to the text control
111 void WriteText(const wxString
& text
);
118 MyThread::MyThread(MyFrame
*frame
)
125 void MyThread::WriteText(const wxString
& text
)
129 // before doing any GUI calls we must ensure that this thread is the only
136 m_frame
->WriteText(msg
);
141 void MyThread::OnExit()
143 wxCriticalSectionLocker
locker(wxGetApp().m_critsect
);
145 wxGetApp().m_threads
.Remove(this);
148 void *MyThread::Entry()
152 text
.Printf("Thread 0x%x started (priority = %d).\n",
153 GetId(), GetPriority());
156 for ( m_count
= 0; m_count
< 10; m_count
++ )
158 // check if we were asked to exit
162 text
.Printf("[%u] Thread 0x%x here.\n", m_count
, GetId());
165 // wxSleep() can't be called from non-GUI thread!
166 wxThread::Sleep(1000);
169 text
.Printf("Thread 0x%x finished.\n", GetId());
175 // ID for the menu commands
182 TEST_START_THREAD
= 201,
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
)
199 EVT_IDLE(MyFrame::OnIdle
)
202 // `Main program' equivalent, creating windows and returning main app frame
205 // Create the main frame window
206 MyFrame
*frame
= new MyFrame((wxFrame
*)NULL
, "wxWindows threads sample",
210 wxMenu
*file_menu
= new wxMenu
;
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");
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
);
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
))
243 m_nRunning
= m_nCount
= 0;
247 m_txtctrl
= new wxTextCtrl(this, -1, "", wxPoint(0, 0), wxSize(0, 0),
248 wxTE_MULTILINE
| wxTE_READONLY
);
252 MyThread
*MyFrame::CreateThread()
254 MyThread
*thread
= new MyThread(this);
256 if ( thread
->Create() != wxTHREAD_NO_ERROR
)
258 wxLogError("Can't create thread!");
261 wxCriticalSectionLocker
enter(wxGetApp().m_critsect
);
262 wxGetApp().m_threads
.Add(thread
);
267 void MyFrame::OnStartThreads(wxCommandEvent
& WXUNUSED(event
) )
269 static long s_num
= 10;
271 s_num
= wxGetNumberFromUser("How many threads to start: ", "",
272 "wxThread sample", s_num
, 1, 10000, this);
280 size_t count
= (size_t)s_num
, n
;
282 wxArrayThread threads
;
284 // first create them all...
285 for ( n
= 0; n
< count
; n
++ )
287 wxThread
*thr
= CreateThread();
289 // we want to show the effect of SetPriority(): the first thread will
290 // have the lowest priority, the second - the highest, all the rest
293 thr
->SetPriority(WXTHREAD_MIN_PRIORITY
);
295 thr
->SetPriority(WXTHREAD_MAX_PRIORITY
);
297 thr
->SetPriority(WXTHREAD_DEFAULT_PRIORITY
);
303 msg
.Printf("%d new threads created.", count
);
304 SetStatusText(msg
, 1);
306 // ...and then start them
307 for ( n
= 0; n
< count
; n
++ )
313 void MyFrame::OnStartThread(wxCommandEvent
& WXUNUSED(event
) )
315 MyThread
*thread
= CreateThread();
317 if ( thread
->Run() != wxTHREAD_NO_ERROR
)
319 wxLogError("Can't start thread!");
322 SetStatusText("New thread started.", 1);
325 void MyFrame::OnStopThread(wxCommandEvent
& WXUNUSED(event
) )
327 // stop the last thread
328 if ( wxGetApp().m_threads
.IsEmpty() )
330 wxLogError("No thread to stop!");
334 wxGetApp().m_critsect
.Enter();
336 wxThread
*thread
= wxGetApp().m_threads
.Last();
338 // it's important to leave critical section before calling Delete()
339 // because delete will (implicitly) call OnExit() which also tries
340 // to enter the same crit section - would dead lock.
341 wxGetApp().m_critsect
.Leave();
345 SetStatusText("Thread stopped.", 1);
349 void MyFrame::OnResumeThread(wxCommandEvent
& WXUNUSED(event
) )
351 wxCriticalSectionLocker
enter(wxGetApp().m_critsect
);
353 // resume first suspended thread
354 size_t n
= 0, count
= wxGetApp().m_threads
.Count();
355 while ( n
< count
&& !wxGetApp().m_threads
[n
]->IsPaused() )
360 wxLogError("No thread to resume!");
364 wxGetApp().m_threads
[n
]->Resume();
366 SetStatusText("Thread resumed.", 1);
370 void MyFrame::OnPauseThread(wxCommandEvent
& WXUNUSED(event
) )
372 wxCriticalSectionLocker
enter(wxGetApp().m_critsect
);
374 // pause last running thread
375 int n
= wxGetApp().m_threads
.Count() - 1;
376 while ( n
>= 0 && !wxGetApp().m_threads
[n
]->IsRunning() )
381 wxLogError("No thread to pause!");
385 wxGetApp().m_threads
[n
]->Pause();
387 SetStatusText("Thread paused.", 1);
391 // set the frame title indicating the current number of threads
392 void MyFrame::OnIdle(wxIdleEvent
&event
)
394 // update the counts of running/total threads
396 nCount
= wxGetApp().m_threads
.Count();
397 for ( size_t n
= 0; n
< nCount
; n
++ )
399 if ( wxGetApp().m_threads
[n
]->IsRunning() )
403 if ( nCount
!= m_nCount
|| nRunning
!= m_nRunning
)
405 m_nRunning
= nRunning
;
408 wxLogStatus(this, "%u threads total, %u running.", nCount
, nRunning
);
410 //else: avoid flicker - don't print anything
413 void MyFrame::OnQuit(wxCommandEvent
& WXUNUSED(event
) )
415 size_t count
= wxGetApp().m_threads
.Count();
416 for ( size_t i
= 0; i
< count
; i
++ )
418 wxGetApp().m_threads
[0]->Delete();
424 void MyFrame::OnAbout(wxCommandEvent
& WXUNUSED(event
) )
426 wxMessageDialog
dialog(this, "wxWindows multithreaded application sample\n"
427 "(c) 1998 Julian Smart, Guilhem Lavaux\n"
428 "(c) 1999 Vadim Zeitlin",
429 "About wxThread sample",
430 wxOK
| wxICON_INFORMATION
);
435 void MyFrame::OnClear(wxCommandEvent
& WXUNUSED(event
))