X-Git-Url: https://git.saurik.com/wxWidgets.git/blobdiff_plain/81f1bb400ab97cdd1d776e1129db2b0fa567819c..3b322b4a1f58b62393a6531dd4466902df3dbe00:/samples/thread/test.cpp?ds=sidebyside diff --git a/samples/thread/test.cpp b/samples/thread/test.cpp index 7d2c088b4f..5788b0caa2 100644 --- a/samples/thread/test.cpp +++ b/samples/thread/test.cpp @@ -10,11 +10,8 @@ ///////////////////////////////////////////////////////////////////////////// /* - TODO: - - 1. show how SetPriority() works. - 2. use worker threads to update progress controls instead of writing - messages - it will be more visual + TODO: use worker threads to update progress controls instead of writing + messages - it will be more visual */ #ifdef __GNUG__ @@ -41,15 +38,26 @@ #include "wx/dynarray.h" #include "wx/time.h" +class MyThread; +WX_DEFINE_ARRAY(wxThread *, wxArrayThread); + // Define a new application type class MyApp : public wxApp { public: - bool OnInit(); + virtual bool OnInit(); + +public: + // all the threads currently alive - as soon as the thread terminates, it's + // removed from the array + wxArrayThread m_threads; + + // crit section protects access to all of the arrays below + wxCriticalSection m_critsect; }; -class MyThread; -WX_DEFINE_ARRAY(wxThread *, wxArrayThread); +// Create a new application object +IMPLEMENT_APP(MyApp) // Define a new frame type class MyFrame: public wxFrame @@ -71,35 +79,16 @@ public: void OnStopThread(wxCommandEvent& event); void OnPauseThread(wxCommandEvent& event); void OnResumeThread(wxCommandEvent& event); + + void OnStartWorker(wxCommandEvent& event); + void OnWorkerEvent(wxCommandEvent& event); void OnIdle(wxIdleEvent &event); - // called by dying thread _in_that_thread_context_ - void OnThreadExit(wxThread *thread); - private: // helper function - creates a new thread (but doesn't run it) MyThread *CreateThread(); - - // crit section protects access to all of the arrays below - wxCriticalSection m_critsect; - - // all the threads currently alive - as soon as the thread terminates, it's - // removed from the array - wxArrayThread m_threads; - - // both of these arrays are only valid between 2 iterations of OnIdle(), - // they're cleared each time it is excuted. - - // the array of threads which finished (either because they did their work - // or because they were explicitly stopped) - wxArrayThread m_terminated; - // the array of threads which were stopped by the user and not terminated - // by themselves - these threads shouldn't be Delete()d second time from - // OnIdle() - wxArrayThread m_stopped; - // just some place to put our messages in wxTextCtrl *m_txtctrl; @@ -109,6 +98,26 @@ private: DECLARE_EVENT_TABLE() }; +// ID for the menu commands +enum +{ + TEST_QUIT = 1, + TEST_TEXT = 101, + TEST_ABOUT, + TEST_CLEAR, + TEST_START_THREAD = 201, + TEST_START_THREADS, + TEST_STOP_THREAD, + TEST_PAUSE_THREAD, + TEST_RESUME_THREAD, + TEST_START_WORKER, + WORKER_EVENT // this one gets sent from the worker thread +}; + +//-------------------------------------------------- +// GUI thread +//-------------------------------------------------- + class MyThread : public wxThread { public: @@ -142,22 +151,28 @@ void MyThread::WriteText(const wxString& text) // before doing any GUI calls we must ensure that this thread is the only // one doing it! - wxMutexGuiLocker guiLocker; - msg << wxTime().FormatTime() << ": " << text; + wxMutexGuiEnter(); + + msg << text; m_frame->WriteText(msg); + + wxMutexGuiLeave(); } void MyThread::OnExit() { - m_frame->OnThreadExit(this); + wxCriticalSectionLocker locker(wxGetApp().m_critsect); + + wxGetApp().m_threads.Remove(this); } void *MyThread::Entry() { wxString text; - text.Printf("Thread 0x%x started.\n", GetID()); + text.Printf("Thread 0x%x started (priority = %d).\n", + GetId(), GetPriority()); WriteText(text); for ( m_count = 0; m_count < 10; m_count++ ) @@ -166,33 +181,84 @@ void *MyThread::Entry() if ( TestDestroy() ) break; - text.Printf("[%u] Thread 0x%x here.\n", m_count, GetID()); + text.Printf("[%u] Thread 0x%x here.\n", m_count, GetId()); WriteText(text); // wxSleep() can't be called from non-GUI thread! wxThread::Sleep(1000); } - text.Printf("Thread 0x%x finished.\n", GetID()); + text.Printf("Thread 0x%x finished.\n", GetId()); WriteText(text); return NULL; } -// ID for the menu commands -enum +//-------------------------------------------------- +// worker thread +//-------------------------------------------------- + +class MyWorkerThread : public wxThread { - TEST_QUIT = 1, - TEST_TEXT = 101, - TEST_ABOUT, - TEST_CLEAR, - TEST_START_THREAD = 201, - TEST_START_THREADS, - TEST_STOP_THREAD, - TEST_PAUSE_THREAD, - TEST_RESUME_THREAD +public: + MyWorkerThread(MyFrame *frame); + + // thread execution starts here + virtual void *Entry(); + + // called when the thread exits - whether it terminates normally or is + // stopped with Delete() (but not when it is Kill()ed!) + virtual void OnExit(); + +public: + MyFrame *m_frame; + size_t m_count; }; +MyWorkerThread::MyWorkerThread(MyFrame *frame) + : wxThread() +{ + m_frame = frame; + m_count = 0; +} + +void MyWorkerThread::OnExit() +{ +} + +void *MyWorkerThread::Entry() +{ + for ( m_count = 0; m_count < 10; m_count++ ) + { + // check if we were asked to exit + if ( TestDestroy() ) + break; + + wxString text; + text.Printf("[%u] Thread 0x%x here!!", m_count, GetId()); + + // create any type of command event here + wxCommandEvent event( wxEVT_COMMAND_MENU_SELECTED, WORKER_EVENT ); + event.SetInt( WORKER_EVENT ); + event.SetString( text ); + + // send in a thread-safe way + wxPostEvent( m_frame, event ); + + // same as: + // m_frame->AddPendingEvent( event ); + + // wxSleep() can't be called from non-main thread! + wxThread::Sleep(1000); + } + + return NULL; +} + +//-------------------------------------------------- +// main program +//-------------------------------------------------- + BEGIN_EVENT_TABLE(MyFrame, wxFrame) EVT_MENU(TEST_QUIT, MyFrame::OnQuit) EVT_MENU(TEST_ABOUT, MyFrame::OnAbout) @@ -202,13 +268,13 @@ BEGIN_EVENT_TABLE(MyFrame, wxFrame) EVT_MENU(TEST_STOP_THREAD, MyFrame::OnStopThread) EVT_MENU(TEST_PAUSE_THREAD, MyFrame::OnPauseThread) EVT_MENU(TEST_RESUME_THREAD, MyFrame::OnResumeThread) + + EVT_MENU(TEST_START_WORKER, MyFrame::OnStartWorker) + EVT_MENU(WORKER_EVENT, MyFrame::OnWorkerEvent) EVT_IDLE(MyFrame::OnIdle) END_EVENT_TABLE() -// Create a new application object -IMPLEMENT_APP (MyApp) - // `Main program' equivalent, creating windows and returning main app frame bool MyApp::OnInit() { @@ -219,21 +285,24 @@ bool MyApp::OnInit() // Make a menubar wxMenu *file_menu = new wxMenu; - file_menu->Append(TEST_CLEAR, "&Clear log"); + file_menu->Append(TEST_CLEAR, "&Clear log\tCtrl-L"); file_menu->AppendSeparator(); file_menu->Append(TEST_ABOUT, "&About"); file_menu->AppendSeparator(); - file_menu->Append(TEST_QUIT, "E&xit"); + file_menu->Append(TEST_QUIT, "E&xit\tAlt-X"); wxMenuBar *menu_bar = new wxMenuBar; menu_bar->Append(file_menu, "&File"); wxMenu *thread_menu = new wxMenu; - thread_menu->Append(TEST_START_THREAD, "&Start a new thread"); + thread_menu->Append(TEST_START_THREAD, "&Start a new thread\tCtrl-N"); thread_menu->Append(TEST_START_THREADS, "Start &many threads at once"); - thread_menu->Append(TEST_STOP_THREAD, "S&top a running thread"); + thread_menu->Append(TEST_STOP_THREAD, "S&top a running thread\tCtrl-S"); thread_menu->AppendSeparator(); - thread_menu->Append(TEST_PAUSE_THREAD, "&Pause a running thread"); - thread_menu->Append(TEST_RESUME_THREAD, "&Resume suspended thread"); + thread_menu->Append(TEST_PAUSE_THREAD, "&Pause a running thread\tCtrl-P"); + thread_menu->Append(TEST_RESUME_THREAD, "&Resume suspended thread\tCtrl-R"); + thread_menu->AppendSeparator(); + thread_menu->Append(TEST_START_WORKER, "Start &worker thread\tCtrl-W"); + menu_bar->Append(thread_menu, "&Thread"); frame->SetMenuBar(menu_bar); @@ -268,32 +337,45 @@ MyThread *MyFrame::CreateThread() wxLogError("Can't create thread!"); } - wxCriticalSectionLocker enter(m_critsect); - m_threads.Add(thread); + wxCriticalSectionLocker enter(wxGetApp().m_critsect); + wxGetApp().m_threads.Add(thread); return thread; } void MyFrame::OnStartThreads(wxCommandEvent& WXUNUSED(event) ) { - static wxString s_str; - s_str = wxGetTextFromUser("How many threads to start: ", - "wxThread sample", - s_str, this); - if ( s_str.IsEmpty() ) - return; + static long s_num = 10; + + s_num = wxGetNumberFromUser("How many threads to start: ", "", + "wxThread sample", s_num, 1, 10000, this); + if ( s_num == -1 ) + { + s_num = 10; - size_t count, n; - sscanf(s_str, "%u", &count); - if ( count == 0 ) return; + } + + size_t count = (size_t)s_num, n; wxArrayThread threads; // first create them all... for ( n = 0; n < count; n++ ) { - threads.Add(CreateThread()); + wxThread *thr = CreateThread(); + + // we want to show the effect of SetPriority(): the first thread will + // have the lowest priority, the second - the highest, all the rest + // the normal one + if ( n == 0 ) + thr->SetPriority(WXTHREAD_MIN_PRIORITY); + else if ( n == 1 ) + thr->SetPriority(WXTHREAD_MAX_PRIORITY); + else + thr->SetPriority(WXTHREAD_DEFAULT_PRIORITY); + + threads.Add(thr); } wxString msg; @@ -322,21 +404,20 @@ void MyFrame::OnStartThread(wxCommandEvent& WXUNUSED(event) ) void MyFrame::OnStopThread(wxCommandEvent& WXUNUSED(event) ) { // stop the last thread - if ( m_threads.IsEmpty() ) + if ( wxGetApp().m_threads.IsEmpty() ) { wxLogError("No thread to stop!"); } else { - m_critsect.Enter(); + wxGetApp().m_critsect.Enter(); - wxThread *thread = m_threads.Last(); - m_stopped.Add(thread); + wxThread *thread = wxGetApp().m_threads.Last(); // it's important to leave critical section before calling Delete() - // because delete will (implicitly) call OnThreadExit() which also tries + // because delete will (implicitly) call OnExit() which also tries // to enter the same crit section - would dead lock. - m_critsect.Leave(); + wxGetApp().m_critsect.Leave(); thread->Delete(); @@ -346,11 +427,11 @@ void MyFrame::OnStopThread(wxCommandEvent& WXUNUSED(event) ) void MyFrame::OnResumeThread(wxCommandEvent& WXUNUSED(event) ) { - wxCriticalSectionLocker enter(m_critsect); + wxCriticalSectionLocker enter(wxGetApp().m_critsect); // resume first suspended thread - size_t n = 0, count = m_threads.Count(); - while ( n < count && !m_threads[n]->IsPaused() ) + size_t n = 0, count = wxGetApp().m_threads.Count(); + while ( n < count && !wxGetApp().m_threads[n]->IsPaused() ) n++; if ( n == count ) @@ -359,7 +440,7 @@ void MyFrame::OnResumeThread(wxCommandEvent& WXUNUSED(event) ) } else { - m_threads[n]->Resume(); + wxGetApp().m_threads[n]->Resume(); SetStatusText("Thread resumed.", 1); } @@ -367,11 +448,11 @@ void MyFrame::OnResumeThread(wxCommandEvent& WXUNUSED(event) ) void MyFrame::OnPauseThread(wxCommandEvent& WXUNUSED(event) ) { - wxCriticalSectionLocker enter(m_critsect); + wxCriticalSectionLocker enter(wxGetApp().m_critsect); // pause last running thread - int n = m_threads.Count() - 1; - while ( n >= 0 && !m_threads[n]->IsRunning() ) + int n = wxGetApp().m_threads.Count() - 1; + while ( n >= 0 && !wxGetApp().m_threads[n]->IsRunning() ) n--; if ( n < 0 ) @@ -380,8 +461,8 @@ void MyFrame::OnPauseThread(wxCommandEvent& WXUNUSED(event) ) } else { - m_threads[n]->Pause(); - + wxGetApp().m_threads[n]->Pause(); + SetStatusText("Thread paused.", 1); } } @@ -389,29 +470,12 @@ void MyFrame::OnPauseThread(wxCommandEvent& WXUNUSED(event) ) // set the frame title indicating the current number of threads void MyFrame::OnIdle(wxIdleEvent &event) { - // first wait for all the threads which dies since the last call - { - wxCriticalSectionLocker enter(m_critsect); - - size_t nCount = m_terminated.GetCount(); - for ( size_t n = 0; n < nCount; n++ ) - { - // don't delete the threads which were stopped - they were already - // deleted in OnStopThread() - wxThread *thread = m_terminated[n]; - if ( m_stopped.Index(thread) == wxNOT_FOUND ) - thread->Delete(); - } - - m_stopped.Empty(); - m_terminated.Empty(); - } - + // update the counts of running/total threads size_t nRunning = 0, - nCount = m_threads.Count(); + nCount = wxGetApp().m_threads.Count(); for ( size_t n = 0; n < nCount; n++ ) { - if ( m_threads[n]->IsRunning() ) + if ( wxGetApp().m_threads[n]->IsRunning() ) nRunning++; } @@ -427,10 +491,10 @@ void MyFrame::OnIdle(wxIdleEvent &event) void MyFrame::OnQuit(wxCommandEvent& WXUNUSED(event) ) { - size_t count = m_threads.Count(); + size_t count = wxGetApp().m_threads.Count(); for ( size_t i = 0; i < count; i++ ) { - m_threads[i]->Delete(); + wxGetApp().m_threads[0]->Delete(); } Close(TRUE); @@ -440,7 +504,8 @@ void MyFrame::OnAbout(wxCommandEvent& WXUNUSED(event) ) { wxMessageDialog dialog(this, "wxWindows multithreaded application sample\n" "(c) 1998 Julian Smart, Guilhem Lavaux\n" - "(c) 1999 Vadim Zeitlin", + "(c) 1999 Vadim Zeitlin\n" + "(c) 2000 Robert Roebling", "About wxThread sample", wxOK | wxICON_INFORMATION); @@ -452,10 +517,22 @@ void MyFrame::OnClear(wxCommandEvent& WXUNUSED(event)) m_txtctrl->Clear(); } -void MyFrame::OnThreadExit(wxThread *thread) +void MyFrame::OnStartWorker(wxCommandEvent& WXUNUSED(event)) { - wxCriticalSectionLocker enter(m_critsect); + MyWorkerThread *thread = new MyWorkerThread(this); + + if ( thread->Create() != wxTHREAD_NO_ERROR ) + { + wxLogError("Can't create thread!"); + } + + thread->Run(); +} - m_threads.Remove(thread); - m_terminated.Add(thread); +void MyFrame::OnWorkerEvent(wxCommandEvent& event) +{ + WriteText( "Got message from worker thread: " ); + WriteText( event.GetString() ); + WriteText( "\n" ); } +