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"
44 // Define a new application type
45 class MyApp
: public wxApp
52 WX_DEFINE_ARRAY(wxThread
*, wxArrayThread
);
54 // Define a new frame type
55 class MyFrame
: public wxFrame
59 MyFrame(wxFrame
*frame
, const wxString
& title
, int x
, int y
, int w
, int h
);
62 void WriteText(const wxString
& text
) { m_txtctrl
->WriteText(text
); }
65 void OnQuit(wxCommandEvent
& event
);
66 void OnAbout(wxCommandEvent
& event
);
67 void OnClear(wxCommandEvent
& event
);
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
);
75 void OnIdle(wxIdleEvent
&event
);
76 bool OnClose() { return TRUE
; }
78 // called by dying thread _in_that_thread_context_
79 void OnThreadExit(wxThread
*thread
);
82 // helper function - creates a new thread (but doesn't run it)
83 MyThread
*CreateThread();
85 // crit section protects access to all of the arrays below
86 wxCriticalSection m_critsect
;
88 // all the threads currently alive - as soon as the thread terminates, it's
89 // removed from the array
90 wxArrayThread m_threads
;
92 // both of these arrays are only valid between 2 iterations of OnIdle(),
93 // they're cleared each time it is excuted.
95 // the array of threads which finished (either because they did their work
96 // or because they were explicitly stopped)
97 wxArrayThread m_terminated
;
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
102 wxArrayThread m_stopped
;
104 // just some place to put our messages in
105 wxTextCtrl
*m_txtctrl
;
107 // remember the number of running threads and total number of threads
108 size_t m_nRunning
, m_nCount
;
110 DECLARE_EVENT_TABLE()
113 class MyThread
: public wxThread
116 MyThread(MyFrame
*frame
);
118 // thread execution starts here
119 virtual void *Entry();
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();
125 // write something to the text control
126 void WriteText(const wxString
& text
);
133 MyThread::MyThread(MyFrame
*frame
)
140 void MyThread::WriteText(const wxString
& text
)
143 msg
<< wxTime().FormatTime() << ": " << text
;
145 // before doing any GUI calls we must ensure that this thread is the only
147 wxMutexGuiLocker guiLocker
;
149 m_frame
->WriteText(msg
);
152 void MyThread::OnExit()
154 m_frame
->OnThreadExit(this);
157 void *MyThread::Entry()
161 text
.Printf("Thread 0x%x started.\n", GetID());
164 for ( m_count
= 0; m_count
< 10; m_count
++ )
166 // check if we were asked to exit
170 text
.Printf("[%u] Thread 0x%x here.\n", m_count
, GetID());
173 // wxSleep() can't be called from non-GUI thread!
174 wxThread::Sleep(1000);
177 text
.Printf("Thread 0x%x finished.\n", GetID());
183 // ID for the menu commands
190 TEST_START_THREAD
= 201,
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
)
207 EVT_IDLE(MyFrame::OnIdle
)
210 // Create a new application object
211 IMPLEMENT_APP (MyApp
)
213 // `Main program' equivalent, creating windows and returning main app frame
216 // Create the main frame window
217 MyFrame
*frame
= new MyFrame((wxFrame
*)NULL
, "wxWindows threads sample",
221 wxMenu
*file_menu
= new wxMenu
;
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");
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
);
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
))
254 m_nRunning
= m_nCount
= 0;
258 m_txtctrl
= new wxTextCtrl(this, -1, "", wxPoint(0, 0), wxSize(0, 0),
259 wxTE_MULTILINE
| wxTE_READONLY
);
263 MyThread
*MyFrame::CreateThread()
265 MyThread
*thread
= new MyThread(this);
267 if ( thread
->Create() != wxTHREAD_NO_ERROR
)
269 wxLogError("Can't create thread!");
272 wxCriticalSectionLocker
enter(m_critsect
);
273 m_threads
.Add(thread
);
278 void MyFrame::OnStartThreads(wxCommandEvent
& WXUNUSED(event
) )
280 static wxString s_str
;
281 s_str
= wxGetTextFromUser("How many threads to start: ",
284 if ( s_str
.IsEmpty() )
288 sscanf(s_str
, "%u", &count
);
292 wxArrayThread threads
;
294 // first create them all...
295 for ( n
= 0; n
< count
; n
++ )
297 threads
.Add(CreateThread());
301 msg
.Printf("%d new threads created.", count
);
302 SetStatusText(msg
, 1);
304 // ...and then start them
305 for ( n
= 0; n
< count
; n
++ )
311 void MyFrame::OnStartThread(wxCommandEvent
& WXUNUSED(event
) )
313 MyThread
*thread
= CreateThread();
315 if ( thread
->Run() != wxTHREAD_NO_ERROR
)
317 wxLogError("Can't start thread!");
320 SetStatusText("New thread started.", 1);
323 void MyFrame::OnStopThread(wxCommandEvent
& WXUNUSED(event
) )
325 // stop the last thread
326 if ( m_threads
.IsEmpty() )
328 wxLogError("No thread to stop!");
334 wxThread
*thread
= m_threads
.Last();
335 m_stopped
.Add(thread
);
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.
344 SetStatusText("Thread stopped.", 1);
348 void MyFrame::OnResumeThread(wxCommandEvent
& WXUNUSED(event
) )
350 wxCriticalSectionLocker
enter(m_critsect
);
352 // resume first suspended thread
353 size_t n
= 0, count
= m_threads
.Count();
354 while ( n
< count
&& !m_threads
[n
]->IsPaused() )
359 wxLogError("No thread to resume!");
363 m_threads
[n
]->Resume();
365 SetStatusText("Thread resumed.", 1);
369 void MyFrame::OnPauseThread(wxCommandEvent
& WXUNUSED(event
) )
371 wxCriticalSectionLocker
enter(m_critsect
);
373 // pause last running thread
374 int n
= m_threads
.Count() - 1;
375 while ( n
>= 0 && !m_threads
[n
]->IsRunning() )
380 wxLogError("No thread to pause!");
384 m_threads
[n
]->Pause();
386 SetStatusText("Thread paused.", 1);
390 // set the frame title indicating the current number of threads
391 void MyFrame::OnIdle(wxIdleEvent
&event
)
393 // first wait for all the threads which dies since the last call
395 wxCriticalSectionLocker
enter(m_critsect
);
397 size_t nCount
= m_terminated
.GetCount();
398 for ( size_t n
= 0; n
< nCount
; n
++ )
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
)
408 m_terminated
.Empty();
412 nCount
= m_threads
.Count();
413 for ( size_t n
= 0; n
< nCount
; n
++ )
415 if ( m_threads
[n
]->IsRunning() )
419 if ( nCount
!= m_nCount
|| nRunning
!= m_nRunning
)
421 m_nRunning
= nRunning
;
424 wxLogStatus(this, "%u threads total, %u running.", nCount
, nRunning
);
426 //else: avoid flicker - don't print anything
429 void MyFrame::OnQuit(wxCommandEvent
& WXUNUSED(event
) )
431 size_t count
= m_threads
.Count();
432 for ( size_t i
= 0; i
< count
; i
++ )
434 m_threads
[i
]->Delete();
440 void MyFrame::OnAbout(wxCommandEvent
& WXUNUSED(event
) )
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
);
451 void MyFrame::OnClear(wxCommandEvent
& WXUNUSED(event
))
456 void MyFrame::OnThreadExit(wxThread
*thread
)
458 wxCriticalSectionLocker
enter(m_critsect
);
460 m_threads
.Remove(thread
);
461 m_terminated
.Add(thread
);