Thread fixes (but they still don't work at all...)

git-svn-id: https://svn.wxwidgets.org/svn/wx/wxWidgets/trunk@1309 c3d73ce0-8a6f-49c7-b76d-6d57e0e08775
This commit is contained in:
Vadim Zeitlin
1999-01-02 22:55:03 +00:00
parent d524867f4c
commit 3222fde2af
4 changed files with 439 additions and 274 deletions

View File

@@ -120,7 +120,7 @@
// since you may well need to output // since you may well need to output
// an error log in a production // an error log in a production
// version (or non-debugging beta) // version (or non-debugging beta)
#define wxUSE_GLOBAL_MEMORY_OPERATORS 1 #define wxUSE_GLOBAL_MEMORY_OPERATORS 0
// In debug mode, cause new and delete to be redefined globally. // In debug mode, cause new and delete to be redefined globally.
// If this causes problems (e.g. link errors), set this to 0. // If this causes problems (e.g. link errors), set this to 0.
@@ -150,11 +150,14 @@
// but you can't mix them. Set to 1 for <iostream.h>, // but you can't mix them. Set to 1 for <iostream.h>,
// 0 for <iostream> // 0 for <iostream>
#define wxUSE_WXCONFIG 1 #define wxUSE_WXCONFIG 1
// if enabled, compiles built-in OS independent wxConfig // if enabled, compiles built-in OS independent wxConfig
// class and it's file (any platform) and registry (Win) // class and it's file (any platform) and registry (Win)
// based implementations // based implementations
#define wxUSE_THREADS 1
// support for multithreaded applications: if
// 1, compile in thread classes (thread.h)
// and make the library thread safe
/* /*
* Finer detail * Finer detail
* *

View File

@@ -18,15 +18,20 @@
#include "wx/wxprec.h" #include "wx/wxprec.h"
#ifdef __BORLANDC__ #ifdef __BORLANDC__
#pragma hdrstop #pragma hdrstop
#endif #endif
#ifndef WX_PRECOMP #ifndef WX_PRECOMP
#include "wx/wx.h" #include "wx/wx.h"
#endif #endif
#if !wxUSE_THREADS
#error "This sample requires thread support!"
#endif // wxUSE_THREADS
#include "wx/thread.h" #include "wx/thread.h"
#include "wx/dynarray.h" #include "wx/dynarray.h"
#include "wx/time.h"
// Define a new application type // Define a new application type
class MyApp: public wxApp class MyApp: public wxApp
@@ -57,7 +62,8 @@ public:
void OnResumeThread(wxCommandEvent& event); void OnResumeThread(wxCommandEvent& event);
void OnSize(wxSizeEvent &event); void OnSize(wxSizeEvent &event);
bool OnClose(void) { return TRUE; } void OnIdle(wxIdleEvent &event);
bool OnClose() { return TRUE; }
public: public:
wxArrayThread m_threads; wxArrayThread m_threads;
@@ -73,7 +79,11 @@ class MyThread: public wxThread
public: public:
MyThread(MyFrame *frame); MyThread(MyFrame *frame);
void *Entry(); // thread execution starts here
virtual void *Entry();
// write something to the text control
void WriteText(const wxString& text);
public: public:
size_t m_count; size_t m_count;
@@ -87,34 +97,56 @@ MyThread::MyThread(MyFrame *frame)
m_frame = frame; m_frame = frame;
} }
void MyThread::WriteText(const wxString& text)
{
wxString msg;
msg << wxTime().FormatTime() << ": " << text;
// before doing any GUI calls we must ensure that this thread is the only
// one doing it!
wxMutexGuiEnter();
m_frame->WriteText(msg);
wxMutexGuiLeave();
}
void *MyThread::Entry() void *MyThread::Entry()
{ {
wxString text; wxString text;
DeferDestroy(TRUE); DeferDestroy(TRUE);
while (1) { text.Printf("Thread 0x%x started.\n", GetID());
TestDestroy(); WriteText(text);
wxMutexGuiEnter();
text.Printf("[%u] Thread 0x%x here.\n", ++m_count, GetID()); for ( m_count = 0; m_count < 20; m_count++ )
m_frame->WriteText(text); {
// check if we were asked to exit
if ( TestDestroy() )
break;
text.Printf("[%u] Thread 0x%x here.\n", m_count, GetID());
WriteText(text);
wxMutexGuiLeave();
wxSleep(1); wxSleep(1);
} }
text.Printf("Thread 0x%x finished.\n", GetID());
WriteText(text);
return NULL; return NULL;
} }
// ID for the menu commands // ID for the menu commands
#define TEST_QUIT 1 enum
#define TEST_TEXT 101 {
#define TEST_ABOUT 102 TEST_QUIT = 1,
#define TEST_START_THREAD 103 TEST_TEXT = 101,
#define TEST_STOP_THREAD 104 TEST_ABOUT = 102,
#define TEST_PAUSE_THREAD 105 TEST_START_THREAD = 103,
#define TEST_RESUME_THREAD 106 TEST_STOP_THREAD = 104,
TEST_PAUSE_THREAD = 105,
TEST_RESUME_THREAD = 106
};
BEGIN_EVENT_TABLE(MyFrame, wxFrame) BEGIN_EVENT_TABLE(MyFrame, wxFrame)
EVT_MENU(TEST_QUIT, MyFrame::OnQuit) EVT_MENU(TEST_QUIT, MyFrame::OnQuit)
@@ -125,17 +157,18 @@ BEGIN_EVENT_TABLE(MyFrame, wxFrame)
EVT_MENU(TEST_RESUME_THREAD, MyFrame::OnResumeThread) EVT_MENU(TEST_RESUME_THREAD, MyFrame::OnResumeThread)
EVT_SIZE(MyFrame::OnSize) EVT_SIZE(MyFrame::OnSize)
EVT_IDLE(MyFrame::OnIdle)
END_EVENT_TABLE() END_EVENT_TABLE()
// Create a new application object // Create a new application object
IMPLEMENT_APP (MyApp) IMPLEMENT_APP (MyApp)
// `Main program' equivalent, creating windows and returning main app frame // `Main program' equivalent, creating windows and returning main app frame
bool MyApp::OnInit(void) bool MyApp::OnInit()
{ {
// Create the main frame window // Create the main frame window
MyFrame *frame = new MyFrame((wxFrame *) NULL, "wxWindows thread sample", MyFrame *frame = new MyFrame((wxFrame *)NULL, "", 50, 50, 450, 340);
50, 50, 450, 340);
// Make a menubar // Make a menubar
wxMenu *file_menu = new wxMenu; wxMenu *file_menu = new wxMenu;
@@ -146,12 +179,12 @@ bool MyApp::OnInit(void)
menu_bar->Append(file_menu, "&File"); menu_bar->Append(file_menu, "&File");
wxMenu *thread_menu = new wxMenu; 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");
thread_menu->Append(TEST_STOP_THREAD, "Stop a running thread"); thread_menu->Append(TEST_STOP_THREAD, "S&top a running thread");
thread_menu->AppendSeparator(); thread_menu->AppendSeparator();
thread_menu->Append(TEST_PAUSE_THREAD, "Pause a running thread"); thread_menu->Append(TEST_PAUSE_THREAD, "&Pause a running thread");
thread_menu->Append(TEST_RESUME_THREAD, "Resume suspended thread"); thread_menu->Append(TEST_RESUME_THREAD, "&Resume suspended thread");
menu_bar->Append(thread_menu, "Thread"); menu_bar->Append(thread_menu, "&Thread");
frame->SetMenuBar(menu_bar); frame->SetMenuBar(menu_bar);
// Show the frame // Show the frame
@@ -167,7 +200,7 @@ MyFrame::MyFrame(wxFrame *frame, char *title, int x, int y, int w, int h)
: wxFrame(frame, -1, title, wxPoint(x, y), wxSize(w, h)) : wxFrame(frame, -1, title, wxPoint(x, y), wxSize(w, h))
{ {
wxPanel *panel = new wxPanel(this, -1, wxPoint(0, 0), wxSize(400, 200), wxPanel *panel = new wxPanel(this, -1, wxPoint(0, 0), wxSize(400, 200),
wxTAB_TRAVERSAL ); wxTAB_TRAVERSAL);
m_txtctrl = new wxTextCtrl(panel, -1, "", wxPoint(10,30), wxSize(390, 190), m_txtctrl = new wxTextCtrl(panel, -1, "", wxPoint(10,30), wxSize(390, 190),
wxTE_MULTILINE); wxTE_MULTILINE);
@@ -191,7 +224,7 @@ void MyFrame::OnStopThread(wxCommandEvent& WXUNUSED(event) )
if (no_thrd < 0) if (no_thrd < 0)
return; return;
delete (m_threads[no_thrd]); delete m_threads[no_thrd];
m_threads.Remove(no_thrd); m_threads.Remove(no_thrd);
} }
@@ -221,7 +254,24 @@ void MyFrame::OnPauseThread(wxCommandEvent& WXUNUSED(event) )
m_threads[n]->Pause(); m_threads[n]->Pause();
} }
void MyFrame::OnSize(wxSizeEvent& event ) // set the frame title indicating the current number of threads
void MyFrame::OnIdle(wxIdleEvent &event)
{
size_t nRunning = 0,
nCount = m_threads.Count();
for ( size_t n = 0; n < nCount; n++ )
{
if ( m_threads[n]->IsRunning() )
nRunning++;
}
wxString title;
title.Printf("wxWindows thread sample (%u threads, %u running).",
nCount, nRunning);
SetTitle(title);
}
void MyFrame::OnSize(wxSizeEvent& event)
{ {
wxFrame::OnSize(event); wxFrame::OnSize(event);
@@ -232,16 +282,18 @@ void MyFrame::OnSize(wxSizeEvent& event )
void MyFrame::OnQuit(wxCommandEvent& WXUNUSED(event) ) void MyFrame::OnQuit(wxCommandEvent& WXUNUSED(event) )
{ {
unsigned int i; for ( size_t i = 0; i < m_threads.Count(); i++ )
for (i=0;i<m_threads.Count();i++) delete m_threads[i];
delete (m_threads[i]);
Close(TRUE); Close(TRUE);
} }
void MyFrame::OnAbout(wxCommandEvent& WXUNUSED(event) ) void MyFrame::OnAbout(wxCommandEvent& WXUNUSED(event) )
{ {
wxMessageDialog dialog(this, "wxThread sample (based on minimal)\nJulian Smart and Guilhem Lavaux", wxMessageDialog dialog(this, "wxThread sample (based on minimal)\n"
"About wxThread sample", wxYES_NO|wxCANCEL); "Julian Smart and Guilhem Lavaux",
"About wxThread sample",
wxOK | wxICON_INFORMATION);
dialog.ShowModal(); dialog.ShowModal();
} }

View File

@@ -38,6 +38,7 @@
#include "wx/msw/private.h" #include "wx/msw/private.h"
#include "wx/log.h" #include "wx/log.h"
#include "wx/module.h" #include "wx/module.h"
#include "wx/thread.h"
#if wxUSE_WX_RESOURCES #if wxUSE_WX_RESOURCES
#include "wx/resource.h" #include "wx/resource.h"
@@ -844,13 +845,13 @@ bool wxApp::ProcessMessage(WXMSG *Msg)
void wxApp::OnIdle(wxIdleEvent& event) void wxApp::OnIdle(wxIdleEvent& event)
{ {
static bool inOnIdle = FALSE; static bool s_inOnIdle = FALSE;
// Avoid recursion (via ProcessEvent default case) // Avoid recursion (via ProcessEvent default case)
if (inOnIdle) if ( s_inOnIdle )
return; return;
inOnIdle = TRUE; s_inOnIdle = TRUE;
// 'Garbage' collection of windows deleted with Close(). // 'Garbage' collection of windows deleted with Close().
DeletePendingObjects(); DeletePendingObjects();
@@ -861,13 +862,19 @@ void wxApp::OnIdle(wxIdleEvent& event)
pLog->Flush(); pLog->Flush();
// Send OnIdle events to all windows // Send OnIdle events to all windows
bool needMore = SendIdleEvents(); if ( SendIdleEvents() )
// bool needMore = FALSE; {
// SendIdleEvents() returns TRUE if at least one window requested more
if (needMore) // idle events
event.RequestMore(TRUE); event.RequestMore(TRUE);
}
inOnIdle = FALSE; // give a chance to all other threads to perform GUI calls
wxMutexGuiLeave();
::Sleep(0);
wxMutexGuiEnter();
s_inOnIdle = FALSE;
} }
// Send idle event to all top-level windows // Send idle event to all top-level windows
@@ -883,6 +890,7 @@ bool wxApp::SendIdleEvents()
node = node->Next(); node = node->Next();
} }
return needMore; return needMore;
} }

View File

@@ -10,47 +10,63 @@
///////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////
#ifdef __GNUG__ #ifdef __GNUG__
#pragma implementation "thread.h" #pragma implementation "thread.h"
#endif #endif
// this is here to regen the precompiled header in the ide compile otherwise the // ----------------------------------------------------------------------------
// compiler crashes in vc5 (nfi why) // headers
// ----------------------------------------------------------------------------
// For compilers that support precompilation, includes "wx.h". // For compilers that support precompilation, includes "wx.h".
#include "wx/wxprec.h" #include "wx/wxprec.h"
#if defined(__BORLANDC__) #if defined(__BORLANDC__)
#pragma hdrstop #pragma hdrstop
#endif #endif
#ifndef WX_PRECOMP #ifndef WX_PRECOMP
#include "wx/wx.h" #include "wx/wx.h"
#endif #endif
#if wxUSE_THREADS
#include <stdio.h> #include <stdio.h>
#include <windows.h> #include <windows.h>
#include "wx/module.h" #include "wx/module.h"
#include "wx/thread.h" #include "wx/thread.h"
enum thread_state { enum thread_state
{
STATE_IDLE = 0, STATE_IDLE = 0,
STATE_RUNNING, STATE_RUNNING,
STATE_CANCELED, STATE_CANCELED,
STATE_EXITED STATE_EXITED
}; };
///////////////////////////////////////////////////////////////////////////// // ----------------------------------------------------------------------------
// Static variables // static variables
///////////////////////////////////////////////////////////////////////////// // ----------------------------------------------------------------------------
static HANDLE p_mainid; // id of the main thread - the one which can call GUI functions without first
wxMutex *wxMainMutex; // controls access to all GUI functions // calling wxMutexGuiEnter()
static HANDLE s_idMainThread;
///////////////////////////////////////////////////////////////////////////// // critical section which controls access to all GUI functions: any secondary
// Windows implementation // thread (i.e. except the main one) must enter this crit section before doing
///////////////////////////////////////////////////////////////////////////// // any GUI calls
static wxCriticalSection *s_critsectGui;
class wxMutexInternal { // ============================================================================
// Windows implementation of thread classes
// ============================================================================
// ----------------------------------------------------------------------------
// wxMutex implementation
// ----------------------------------------------------------------------------
class wxMutexInternal
{
public: public:
HANDLE p_mutex; HANDLE p_mutex;
}; };
@@ -79,9 +95,24 @@ wxMutexError wxMutex::Lock()
DWORD ret; DWORD ret;
ret = WaitForSingleObject(p_internal->p_mutex, INFINITE); ret = WaitForSingleObject(p_internal->p_mutex, INFINITE);
if (ret == WAIT_ABANDONED) switch ( ret )
{
case WAIT_ABANDONED:
return wxMUTEX_BUSY; return wxMUTEX_BUSY;
case WAIT_OBJECT_0:
// ok
break;
case WAIT_FAILED:
wxLogSysError(_("Couldn't acquire a mutex lock"));
return wxMUTEX_MISC_ERROR;
case WAIT_TIMEOUT:
default:
wxFAIL_MSG("impossible return value in wxMutex::Lock");
}
m_locked++; m_locked++;
return wxMUTEX_NO_ERROR; return wxMUTEX_NO_ERROR;
} }
@@ -104,7 +135,7 @@ wxMutexError wxMutex::Unlock()
m_locked--; m_locked--;
BOOL ret = ReleaseMutex(p_internal->p_mutex); BOOL ret = ReleaseMutex(p_internal->p_mutex);
if ( ret != 0 ) if ( ret == 0 )
{ {
wxLogSysError(_("Couldn't release a mutex")); wxLogSysError(_("Couldn't release a mutex"));
return wxMUTEX_MISC_ERROR; return wxMUTEX_MISC_ERROR;
@@ -113,7 +144,12 @@ wxMutexError wxMutex::Unlock()
return wxMUTEX_NO_ERROR; return wxMUTEX_NO_ERROR;
} }
class wxConditionInternal { // ----------------------------------------------------------------------------
// wxCondition implementation
// ----------------------------------------------------------------------------
class wxConditionInternal
{
public: public:
HANDLE event; HANDLE event;
int waiters; int waiters;
@@ -145,7 +181,8 @@ void wxCondition::Wait(wxMutex& mutex)
mutex.Lock(); mutex.Lock();
} }
bool wxCondition::Wait(wxMutex& mutex, unsigned long sec, bool wxCondition::Wait(wxMutex& mutex,
unsigned long sec,
unsigned long nsec) unsigned long nsec)
{ {
DWORD ret; DWORD ret;
@@ -177,7 +214,54 @@ void wxCondition::Broadcast()
} }
} }
class wxThreadInternal { // ----------------------------------------------------------------------------
// wxCriticalSection implementation
// ----------------------------------------------------------------------------
class wxCriticalSectionInternal
{
public:
// init the critical section object
wxCriticalSectionInternal()
{ ::InitializeCriticalSection(&m_data); }
// implicit cast to the associated data
operator CRITICAL_SECTION *() { return &m_data; }
// free the associated ressources
~wxCriticalSectionInternal()
{ ::DeleteCriticalSection(&m_data); }
private:
CRITICAL_SECTION m_data;
};
wxCriticalSection::wxCriticalSection()
{
m_critsect = new wxCriticalSectionInternal;
}
wxCriticalSection::~wxCriticalSection()
{
delete m_critsect;
}
void wxCriticalSection::Enter()
{
::EnterCriticalSection(*m_critsect);
}
void wxCriticalSection::Leave()
{
::LeaveCriticalSection(*m_critsect);
}
// ----------------------------------------------------------------------------
// wxThread implementation
// ----------------------------------------------------------------------------
class wxThreadInternal
{
public: public:
static DWORD WinThreadStart(LPVOID arg); static DWORD WinThreadStart(LPVOID arg);
@@ -242,10 +326,13 @@ wxThreadError wxThread::Destroy()
if (p_internal->state != STATE_RUNNING) if (p_internal->state != STATE_RUNNING)
return wxTHREAD_NOT_RUNNING; return wxTHREAD_NOT_RUNNING;
if (p_internal->defer == FALSE) if ( p_internal->defer )
TerminateThread(p_internal->thread_id, 0); // soft termination: just set the flag and wait until the thread
else // auto terminates
p_internal->state = STATE_CANCELED; p_internal->state = STATE_CANCELED;
else
// kill the thread
TerminateThread(p_internal->thread_id, 0);
return wxTHREAD_NO_ERROR; return wxTHREAD_NO_ERROR;
} }
@@ -297,10 +384,9 @@ void wxThread::DeferDestroy(bool on)
p_internal->defer = on; p_internal->defer = on;
} }
void wxThread::TestDestroy() bool wxThread::TestDestroy()
{ {
if (p_internal->state == STATE_CANCELED) return p_internal->state == STATE_CANCELED;
ExitThread(0);
} }
void *wxThread::Join() void *wxThread::Join()
@@ -311,10 +397,10 @@ void *wxThread::Join()
return NULL; return NULL;
if (wxThread::IsMain()) if (wxThread::IsMain())
wxMainMutex->Unlock(); s_critsectGui->Leave();
WaitForSingleObject(p_internal->thread_id, INFINITE); WaitForSingleObject(p_internal->thread_id, INFINITE);
if (wxThread::IsMain()) if (wxThread::IsMain())
wxMainMutex->Lock(); s_critsectGui->Enter();
GetExitCodeThread(p_internal->thread_id, &exit_code); GetExitCodeThread(p_internal->thread_id, &exit_code);
CloseHandle(p_internal->thread_id); CloseHandle(p_internal->thread_id);
@@ -341,7 +427,7 @@ bool wxThread::IsAlive() const
bool wxThread::IsMain() bool wxThread::IsMain()
{ {
return (GetCurrentThread() == p_mainid); return (GetCurrentThread() == s_idMainThread);
} }
wxThread::wxThread() wxThread::wxThread()
@@ -360,39 +446,55 @@ wxThread::~wxThread()
delete p_internal; delete p_internal;
} }
// The default callback just joins the thread and throws away the result.
void wxThread::OnExit() void wxThread::OnExit()
{ {
Join();
} }
// GUI mutex functions // ----------------------------------------------------------------------------
// Automatic initialization for thread module
// ----------------------------------------------------------------------------
void WXDLLEXPORT wxMutexGuiEnter() class wxThreadModule : public wxModule
{ {
wxFAIL_MSG("not implemented"); public:
} virtual bool OnInit();
virtual void OnExit();
void WXDLLEXPORT wxMutexGuiLeave() private:
{ DECLARE_DYNAMIC_CLASS(wxThreadModule)
wxFAIL_MSG("not implemented"); };
}
// Automatic initialization
IMPLEMENT_DYNAMIC_CLASS(wxThreadModule, wxModule) IMPLEMENT_DYNAMIC_CLASS(wxThreadModule, wxModule)
bool wxThreadModule::OnInit() bool wxThreadModule::OnInit()
{ {
wxMainMutex = new wxMutex(); s_critsectGui = new wxCriticalSection();
p_mainid = GetCurrentThread(); s_critsectGui->Enter();
wxMainMutex->Lock(); s_idMainThread = GetCurrentThread();
return TRUE; return TRUE;
} }
void wxThreadModule::OnExit() void wxThreadModule::OnExit()
{ {
wxMainMutex->Unlock(); if ( s_critsectGui )
delete wxMainMutex; {
}; s_critsectGui->Leave();
delete s_critsectGui;
s_critsectGui = NULL;
}
}
// under Windows, these functions are implemented usign a critical section and
// not a mutex, so the names are a bit confusing
void WXDLLEXPORT wxMutexGuiEnter()
{
//s_critsectGui->Enter();
}
void WXDLLEXPORT wxMutexGuiLeave()
{
//s_critsectGui->Leave();
}
#endif // wxUSE_THREADS