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 /////////////////////////////////////////////////////////////////////////////
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
21 #pragma implementation "test.cpp"
22 #pragma interface "test.cpp"
25 // For compilers that support precompilation, includes "wx/wx.h".
26 #include "wx/wxprec.h"
37 #error "This sample requires thread support!"
38 #endif // wxUSE_THREADS
40 #include "wx/thread.h"
41 #include "wx/dynarray.h"
45 WX_DEFINE_ARRAY(wxThread
*, wxArrayThread
);
47 // Define a new application type
48 class MyApp
: public wxApp
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
;
61 // Create a new application object
64 // Define a new frame type
65 class MyFrame
: public wxFrame
69 MyFrame(wxFrame
*frame
, const wxString
& title
, int x
, int y
, int w
, int h
);
72 void WriteText(const wxString
& text
) { m_txtctrl
->WriteText(text
); }
75 void OnQuit(wxCommandEvent
& event
);
76 void OnAbout(wxCommandEvent
& event
);
77 void OnClear(wxCommandEvent
& event
);
79 void OnStartThread(wxCommandEvent
& event
);
80 void OnStartThreads(wxCommandEvent
& event
);
81 void OnStopThread(wxCommandEvent
& event
);
82 void OnPauseThread(wxCommandEvent
& event
);
83 void OnResumeThread(wxCommandEvent
& event
);
85 void OnIdle(wxIdleEvent
&event
);
88 // helper function - creates a new thread (but doesn't run it)
89 MyThread
*CreateThread();
92 // just some place to put our messages in
93 wxTextCtrl
*m_txtctrl
;
95 // remember the number of running threads and total number of threads
96 size_t m_nRunning
, m_nCount
;
101 class MyThread
: public wxThread
104 MyThread(MyFrame
*frame
);
106 // thread execution starts here
107 virtual void *Entry();
109 // called when the thread exits - whether it terminates normally or is
110 // stopped with Delete() (but not when it is Kill()ed!)
111 virtual void OnExit();
113 // write something to the text control
114 void WriteText(const wxString
& text
);
121 MyThread::MyThread(MyFrame
*frame
)
128 void MyThread::WriteText(const wxString
& text
)
132 // before doing any GUI calls we must ensure that this thread is the only
137 msg
<< wxTime().FormatTime() << ": " << text
;
139 m_frame
->WriteText(msg
);
144 void MyThread::OnExit()
146 wxCriticalSectionLocker
locker(wxGetApp().m_critsect
);
148 wxGetApp().m_threads
.Remove(this);
151 void *MyThread::Entry()
155 text
.Printf("Thread 0x%x started.\n", GetID());
158 for ( m_count
= 0; m_count
< 10; m_count
++ )
160 // check if we were asked to exit
164 text
.Printf("[%u] Thread 0x%x here.\n", m_count
, GetID());
167 // wxSleep() can't be called from non-GUI thread!
168 wxThread::Sleep(1000);
171 text
.Printf("Thread 0x%x finished.\n", GetID());
177 // ID for the menu commands
184 TEST_START_THREAD
= 201,
191 BEGIN_EVENT_TABLE(MyFrame
, wxFrame
)
192 EVT_MENU(TEST_QUIT
, MyFrame::OnQuit
)
193 EVT_MENU(TEST_ABOUT
, MyFrame::OnAbout
)
194 EVT_MENU(TEST_CLEAR
, MyFrame::OnClear
)
195 EVT_MENU(TEST_START_THREAD
, MyFrame::OnStartThread
)
196 EVT_MENU(TEST_START_THREADS
, MyFrame::OnStartThreads
)
197 EVT_MENU(TEST_STOP_THREAD
, MyFrame::OnStopThread
)
198 EVT_MENU(TEST_PAUSE_THREAD
, MyFrame::OnPauseThread
)
199 EVT_MENU(TEST_RESUME_THREAD
, MyFrame::OnResumeThread
)
201 EVT_IDLE(MyFrame::OnIdle
)
204 // `Main program' equivalent, creating windows and returning main app frame
207 // Create the main frame window
208 MyFrame
*frame
= new MyFrame((wxFrame
*)NULL
, "wxWindows threads sample",
212 wxMenu
*file_menu
= new wxMenu
;
214 file_menu
->Append(TEST_CLEAR
, "&Clear log");
215 file_menu
->AppendSeparator();
216 file_menu
->Append(TEST_ABOUT
, "&About");
217 file_menu
->AppendSeparator();
218 file_menu
->Append(TEST_QUIT
, "E&xit");
219 wxMenuBar
*menu_bar
= new wxMenuBar
;
220 menu_bar
->Append(file_menu
, "&File");
222 wxMenu
*thread_menu
= new wxMenu
;
223 thread_menu
->Append(TEST_START_THREAD
, "&Start a new thread");
224 thread_menu
->Append(TEST_START_THREADS
, "Start &many threads at once");
225 thread_menu
->Append(TEST_STOP_THREAD
, "S&top a running thread");
226 thread_menu
->AppendSeparator();
227 thread_menu
->Append(TEST_PAUSE_THREAD
, "&Pause a running thread");
228 thread_menu
->Append(TEST_RESUME_THREAD
, "&Resume suspended thread");
229 menu_bar
->Append(thread_menu
, "&Thread");
230 frame
->SetMenuBar(menu_bar
);
240 // My frame constructor
241 MyFrame::MyFrame(wxFrame
*frame
, const wxString
& title
,
242 int x
, int y
, int w
, int h
)
243 : wxFrame(frame
, -1, title
, wxPoint(x
, y
), wxSize(w
, h
))
245 m_nRunning
= m_nCount
= 0;
249 m_txtctrl
= new wxTextCtrl(this, -1, "", wxPoint(0, 0), wxSize(0, 0),
250 wxTE_MULTILINE
| wxTE_READONLY
);
254 MyThread
*MyFrame::CreateThread()
256 MyThread
*thread
= new MyThread(this);
258 if ( thread
->Create() != wxTHREAD_NO_ERROR
)
260 wxLogError("Can't create thread!");
263 wxCriticalSectionLocker
enter(wxGetApp().m_critsect
);
264 wxGetApp().m_threads
.Add(thread
);
269 void MyFrame::OnStartThreads(wxCommandEvent
& WXUNUSED(event
) )
271 static wxString s_str
;
272 s_str
= wxGetTextFromUser("How many threads to start: ",
275 if ( s_str
.IsEmpty() )
279 sscanf(s_str
, "%u", &count
);
283 wxArrayThread threads
;
285 // first create them all...
286 for ( n
= 0; n
< count
; n
++ )
288 threads
.Add(CreateThread());
292 msg
.Printf("%d new threads created.", count
);
293 SetStatusText(msg
, 1);
295 // ...and then start them
296 for ( n
= 0; n
< count
; n
++ )
302 void MyFrame::OnStartThread(wxCommandEvent
& WXUNUSED(event
) )
304 MyThread
*thread
= CreateThread();
306 if ( thread
->Run() != wxTHREAD_NO_ERROR
)
308 wxLogError("Can't start thread!");
311 SetStatusText("New thread started.", 1);
314 void MyFrame::OnStopThread(wxCommandEvent
& WXUNUSED(event
) )
316 // stop the last thread
317 if ( wxGetApp().m_threads
.IsEmpty() )
319 wxLogError("No thread to stop!");
323 wxGetApp().m_critsect
.Enter();
325 wxThread
*thread
= wxGetApp().m_threads
.Last();
327 // it's important to leave critical section before calling Delete()
328 // because delete will (implicitly) call OnExit() which also tries
329 // to enter the same crit section - would dead lock.
330 wxGetApp().m_critsect
.Leave();
334 SetStatusText("Thread stopped.", 1);
338 void MyFrame::OnResumeThread(wxCommandEvent
& WXUNUSED(event
) )
340 wxCriticalSectionLocker
enter(wxGetApp().m_critsect
);
342 // resume first suspended thread
343 size_t n
= 0, count
= wxGetApp().m_threads
.Count();
344 while ( n
< count
&& !wxGetApp().m_threads
[n
]->IsPaused() )
349 wxLogError("No thread to resume!");
353 wxGetApp().m_threads
[n
]->Resume();
355 SetStatusText("Thread resumed.", 1);
359 void MyFrame::OnPauseThread(wxCommandEvent
& WXUNUSED(event
) )
361 wxCriticalSectionLocker
enter(wxGetApp().m_critsect
);
363 // pause last running thread
364 int n
= wxGetApp().m_threads
.Count() - 1;
365 while ( n
>= 0 && !wxGetApp().m_threads
[n
]->IsRunning() )
370 wxLogError("No thread to pause!");
374 wxGetApp().m_threads
[n
]->Pause();
376 SetStatusText("Thread paused.", 1);
380 // set the frame title indicating the current number of threads
381 void MyFrame::OnIdle(wxIdleEvent
&event
)
383 // update the counts of running/total threads
385 nCount
= wxGetApp().m_threads
.Count();
386 for ( size_t n
= 0; n
< nCount
; n
++ )
388 if ( wxGetApp().m_threads
[n
]->IsRunning() )
392 if ( nCount
!= m_nCount
|| nRunning
!= m_nRunning
)
394 m_nRunning
= nRunning
;
397 wxLogStatus(this, "%u threads total, %u running.", nCount
, nRunning
);
399 //else: avoid flicker - don't print anything
402 void MyFrame::OnQuit(wxCommandEvent
& WXUNUSED(event
) )
404 size_t count
= wxGetApp().m_threads
.Count();
405 for ( size_t i
= 0; i
< count
; i
++ )
407 wxGetApp().m_threads
[0]->Delete();
413 void MyFrame::OnAbout(wxCommandEvent
& WXUNUSED(event
) )
415 wxMessageDialog
dialog(this, "wxWindows multithreaded application sample\n"
416 "(c) 1998 Julian Smart, Guilhem Lavaux\n"
417 "(c) 1999 Vadim Zeitlin",
418 "About wxThread sample",
419 wxOK
| wxICON_INFORMATION
);
424 void MyFrame::OnClear(wxCommandEvent
& WXUNUSED(event
))