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
// an error log in a production
// 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.
// 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>,
// 0 for <iostream>
#define wxUSE_WXCONFIG 1
// if enabled, compiles built-in OS independent wxConfig
// class and it's file (any platform) and registry (Win)
// 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
*

View File

@@ -25,8 +25,13 @@
#include "wx/wx.h"
#endif
#if !wxUSE_THREADS
#error "This sample requires thread support!"
#endif // wxUSE_THREADS
#include "wx/thread.h"
#include "wx/dynarray.h"
#include "wx/time.h"
// Define a new application type
class MyApp: public wxApp
@@ -57,7 +62,8 @@ public:
void OnResumeThread(wxCommandEvent& event);
void OnSize(wxSizeEvent &event);
bool OnClose(void) { return TRUE; }
void OnIdle(wxIdleEvent &event);
bool OnClose() { return TRUE; }
public:
wxArrayThread m_threads;
@@ -73,7 +79,11 @@ class MyThread: public wxThread
public:
MyThread(MyFrame *frame);
void *Entry();
// thread execution starts here
virtual void *Entry();
// write something to the text control
void WriteText(const wxString& text);
public:
size_t m_count;
@@ -87,34 +97,56 @@ MyThread::MyThread(MyFrame *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()
{
wxString text;
DeferDestroy(TRUE);
while (1) {
TestDestroy();
wxMutexGuiEnter();
text.Printf("Thread 0x%x started.\n", GetID());
WriteText(text);
text.Printf("[%u] Thread 0x%x here.\n", ++m_count, GetID());
m_frame->WriteText(text);
for ( m_count = 0; m_count < 20; m_count++ )
{
// 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);
}
text.Printf("Thread 0x%x finished.\n", GetID());
WriteText(text);
return NULL;
}
// ID for the menu commands
#define TEST_QUIT 1
#define TEST_TEXT 101
#define TEST_ABOUT 102
#define TEST_START_THREAD 103
#define TEST_STOP_THREAD 104
#define TEST_PAUSE_THREAD 105
#define TEST_RESUME_THREAD 106
enum
{
TEST_QUIT = 1,
TEST_TEXT = 101,
TEST_ABOUT = 102,
TEST_START_THREAD = 103,
TEST_STOP_THREAD = 104,
TEST_PAUSE_THREAD = 105,
TEST_RESUME_THREAD = 106
};
BEGIN_EVENT_TABLE(MyFrame, wxFrame)
EVT_MENU(TEST_QUIT, MyFrame::OnQuit)
@@ -125,17 +157,18 @@ BEGIN_EVENT_TABLE(MyFrame, wxFrame)
EVT_MENU(TEST_RESUME_THREAD, MyFrame::OnResumeThread)
EVT_SIZE(MyFrame::OnSize)
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(void)
bool MyApp::OnInit()
{
// Create the main frame window
MyFrame *frame = new MyFrame((wxFrame *) NULL, "wxWindows thread sample",
50, 50, 450, 340);
MyFrame *frame = new MyFrame((wxFrame *)NULL, "", 50, 50, 450, 340);
// Make a menubar
wxMenu *file_menu = new wxMenu;
@@ -146,12 +179,12 @@ bool MyApp::OnInit(void)
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_STOP_THREAD, "Stop a running thread");
thread_menu->Append(TEST_START_THREAD, "&Start a new thread");
thread_menu->Append(TEST_STOP_THREAD, "S&top a running thread");
thread_menu->AppendSeparator();
thread_menu->Append(TEST_PAUSE_THREAD, "Pause a running thread");
thread_menu->Append(TEST_RESUME_THREAD, "Resume suspended thread");
menu_bar->Append(thread_menu, "Thread");
thread_menu->Append(TEST_PAUSE_THREAD, "&Pause a running thread");
thread_menu->Append(TEST_RESUME_THREAD, "&Resume suspended thread");
menu_bar->Append(thread_menu, "&Thread");
frame->SetMenuBar(menu_bar);
// Show the frame
@@ -191,7 +224,7 @@ void MyFrame::OnStopThread(wxCommandEvent& WXUNUSED(event) )
if (no_thrd < 0)
return;
delete (m_threads[no_thrd]);
delete m_threads[no_thrd];
m_threads.Remove(no_thrd);
}
@@ -221,6 +254,23 @@ void MyFrame::OnPauseThread(wxCommandEvent& WXUNUSED(event) )
m_threads[n]->Pause();
}
// 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);
@@ -232,16 +282,18 @@ void MyFrame::OnSize(wxSizeEvent& event )
void MyFrame::OnQuit(wxCommandEvent& WXUNUSED(event) )
{
unsigned int i;
for (i=0;i<m_threads.Count();i++)
delete (m_threads[i]);
for ( size_t i = 0; i < m_threads.Count(); i++ )
delete m_threads[i];
Close(TRUE);
}
void MyFrame::OnAbout(wxCommandEvent& WXUNUSED(event) )
{
wxMessageDialog dialog(this, "wxThread sample (based on minimal)\nJulian Smart and Guilhem Lavaux",
"About wxThread sample", wxYES_NO|wxCANCEL);
wxMessageDialog dialog(this, "wxThread sample (based on minimal)\n"
"Julian Smart and Guilhem Lavaux",
"About wxThread sample",
wxOK | wxICON_INFORMATION);
dialog.ShowModal();
}

View File

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

View File

@@ -13,8 +13,10 @@
#pragma implementation "thread.h"
#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".
#include "wx/wxprec.h"
@@ -26,31 +28,45 @@
#include "wx/wx.h"
#endif
#if wxUSE_THREADS
#include <stdio.h>
#include <windows.h>
#include "wx/module.h"
#include "wx/thread.h"
enum thread_state {
enum thread_state
{
STATE_IDLE = 0,
STATE_RUNNING,
STATE_CANCELED,
STATE_EXITED
};
/////////////////////////////////////////////////////////////////////////////
// Static variables
/////////////////////////////////////////////////////////////////////////////
// ----------------------------------------------------------------------------
// static variables
// ----------------------------------------------------------------------------
static HANDLE p_mainid;
wxMutex *wxMainMutex; // controls access to all GUI functions
// id of the main thread - the one which can call GUI functions without first
// calling wxMutexGuiEnter()
static HANDLE s_idMainThread;
/////////////////////////////////////////////////////////////////////////////
// Windows implementation
/////////////////////////////////////////////////////////////////////////////
// critical section which controls access to all GUI functions: any secondary
// 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:
HANDLE p_mutex;
};
@@ -79,9 +95,24 @@ wxMutexError wxMutex::Lock()
DWORD ret;
ret = WaitForSingleObject(p_internal->p_mutex, INFINITE);
if (ret == WAIT_ABANDONED)
switch ( ret )
{
case WAIT_ABANDONED:
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++;
return wxMUTEX_NO_ERROR;
}
@@ -104,7 +135,7 @@ wxMutexError wxMutex::Unlock()
m_locked--;
BOOL ret = ReleaseMutex(p_internal->p_mutex);
if ( ret != 0 )
if ( ret == 0 )
{
wxLogSysError(_("Couldn't release a mutex"));
return wxMUTEX_MISC_ERROR;
@@ -113,7 +144,12 @@ wxMutexError wxMutex::Unlock()
return wxMUTEX_NO_ERROR;
}
class wxConditionInternal {
// ----------------------------------------------------------------------------
// wxCondition implementation
// ----------------------------------------------------------------------------
class wxConditionInternal
{
public:
HANDLE event;
int waiters;
@@ -145,7 +181,8 @@ void wxCondition::Wait(wxMutex& mutex)
mutex.Lock();
}
bool wxCondition::Wait(wxMutex& mutex, unsigned long sec,
bool wxCondition::Wait(wxMutex& mutex,
unsigned long sec,
unsigned long nsec)
{
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:
static DWORD WinThreadStart(LPVOID arg);
@@ -242,10 +326,13 @@ wxThreadError wxThread::Destroy()
if (p_internal->state != STATE_RUNNING)
return wxTHREAD_NOT_RUNNING;
if (p_internal->defer == FALSE)
TerminateThread(p_internal->thread_id, 0);
else
if ( p_internal->defer )
// soft termination: just set the flag and wait until the thread
// auto terminates
p_internal->state = STATE_CANCELED;
else
// kill the thread
TerminateThread(p_internal->thread_id, 0);
return wxTHREAD_NO_ERROR;
}
@@ -297,10 +384,9 @@ void wxThread::DeferDestroy(bool on)
p_internal->defer = on;
}
void wxThread::TestDestroy()
bool wxThread::TestDestroy()
{
if (p_internal->state == STATE_CANCELED)
ExitThread(0);
return p_internal->state == STATE_CANCELED;
}
void *wxThread::Join()
@@ -311,10 +397,10 @@ void *wxThread::Join()
return NULL;
if (wxThread::IsMain())
wxMainMutex->Unlock();
s_critsectGui->Leave();
WaitForSingleObject(p_internal->thread_id, INFINITE);
if (wxThread::IsMain())
wxMainMutex->Lock();
s_critsectGui->Enter();
GetExitCodeThread(p_internal->thread_id, &exit_code);
CloseHandle(p_internal->thread_id);
@@ -341,7 +427,7 @@ bool wxThread::IsAlive() const
bool wxThread::IsMain()
{
return (GetCurrentThread() == p_mainid);
return (GetCurrentThread() == s_idMainThread);
}
wxThread::wxThread()
@@ -360,39 +446,55 @@ wxThread::~wxThread()
delete p_internal;
}
// The default callback just joins the thread and throws away the result.
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()
{
wxFAIL_MSG("not implemented");
}
// Automatic initialization
private:
DECLARE_DYNAMIC_CLASS(wxThreadModule)
};
IMPLEMENT_DYNAMIC_CLASS(wxThreadModule, wxModule)
bool wxThreadModule::OnInit()
{
wxMainMutex = new wxMutex();
p_mainid = GetCurrentThread();
wxMainMutex->Lock();
s_critsectGui = new wxCriticalSection();
s_critsectGui->Enter();
s_idMainThread = GetCurrentThread();
return TRUE;
}
void wxThreadModule::OnExit()
{
wxMainMutex->Unlock();
delete wxMainMutex;
};
if ( s_critsectGui )
{
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