⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 usersync.cpp

📁 mini http server,可以集成嵌入到程序中,实现简单的web功能
💻 CPP
📖 第 1 页 / 共 5 页
字号:
/*___________________________________________________________________________*\
 *

 Copyright (c) 1997-2003 John Roy, Holger Zimmermann. All rights reserved.

 These sources, libraries and applications are
 FREE FOR COMMERCIAL AND NON-COMMERCIAL USE       
 as long as the following conditions are adhered to.

 Redistribution and use in source and binary forms, with or without
 modification, are permitted provided that the following conditions
 are met:

 1. Redistributions of source code must retain the above copyright
    notice, this list of conditions and the following disclaimer. 

 2. Redistributions in binary form must reproduce the above copyright
    notice, this list of conditions and the following disclaimer in
    the documentation and/or other materials provided with the
    distribution.

 3. The name of the author may not be used to endorse or promote products
    derived from this software without specific prior written permission.

 THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
 WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
 IN NO EVENT SHALL THE AUTHORS OR ITS CONTRIBUTORS BE LIABLE FOR ANY
 DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
 GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
 STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
 OF THE POSSIBILITY OF SUCH DAMAGE.

 *___________________________________________________________________________*|
 *
 * $Source: /cvsroot/pi3web/Pi3Web_200/Source/Platform/UserSync.cpp,v $
 * $Date: 2003/05/13 18:42:14 $
 *
 Description:
	Implementation of user context threads and synchronization 
	facilities.

\*___________________________________________________________________________*/
//$SourceTop:$

#include "OSConfig.h"		/* --- get build options --- */
#include "PlatDefs.h"

/* ---
 Include this file only for builds which use user multithreading
--- */
#if defined(CONFIG_MULTITHREADED) && defined(CONFIG_MT_USER)

/*___________________________________________________________________________*\
 *
 Description:
	Debugging macros
\*___________________________________________________________________________*/
#define DEBUG	40		/* >=40  ugly, verbose and line numbers */
// #define DEBUG	30		/* >=30 ugly verbose runtime logging */
// #define DEBUG	25		/* >=25 more verbose runtime logging */
// #define DEBUG	20		/* >=20 verbose runtime logging */
// #define DEBUG	15		/* >=15 terse runtime logging */
// #define DEBUG	10		/* >=10 verbose logging on catastrophe */
// #define DEBUG	5		/* >0	terse logging on catastrophe */
// #define DEBUG	0		/* ==0 never log */

#if DEBUG>=40
#	define D { CERR << "[" << Platform::GetProcessId() << ":" << \
		(___pTheCurrentThread ? (int)___pTheCurrentThread->GetSystemHandle() \
		: -1 ) << "] " << __FILE__ << \
		": " << __LINE__ << endl; }
#else
#	define D
#endif

#if !defined(CONFIG_CPP_EXCEPTIONS)
#	include <setjmp.h>
#endif

#if defined(CONFIG_OS_POSIX)
	#	include <unistd.h>
	#	include <sys/types.h>
	#	include <sys/time.h>
	#	include <sys/wait.h>
	#	if defined(CONFIG_USE_BSTRING)
	#		include <bstring.h>				/* bzero() used by FD_ZERO */
	#	endif
	# 	if defined(CONFIG_LOCK_FLOCK)
	#		define _BSD_COMPAT			  	/* conflict on SGI, see man flock */
	#		include <sys/file.h>			/* for ::flock() */
	#	endif
#elif defined(CONFIG_OS_WIN16)
	#	if defined(__BORLANDC__)
		/* don't want those borland 'cant inline' messages */
	#		pragma warn -inl
	#	endif
	#
#endif

/*
** include some windows stuff
*/
#if defined(CONFIG_USE_WINSOCK)
extern "C"
	{
	#	include <winsock.h>					/* for timeval, fd_set etc. */
	};
#endif

#include <iostream.h>
#include <time.h>
#include <limits.h>
#include <errno.h>

#include "UserSync.h"
#include "PICompat.h"
#include "Allocate.h"
#include "OSEntity.h"
#include "Platform.h"

#if 0
// LATER
#include <fstream.h>
ofstream ofs( "D:\\DEVEL\\Pi3WEB\\SOURCE\\out.lst" );
#define CERR ofs
#endif
#define CERR cerr

/*___________________________________________________________________________*\
 *
 Declarations:
\*___________________________________________________________________________*/
/*
** Stack sizes
**
**		0x04000		=		16K
** 		0x08000		=		32K
**		0x10000		=		64K
**		0x18000		=		96K
**		0x20000		=	   128K
**
*/
#if defined(CONFIG_OS_WIN16)
	/*
	** Small stacksize
	*/
#	define PI_DEFAULTSTACKSIZE	0x2000
#else
	/*
	** Flat memory models
	*/
#	define PI_DEFAULTSTACKSIZE	0x10000
#endif

#define PI_MAXTHREADKEYS		128			/* Maximum number of keys */

/* ---
size of register context measured in units of size_t size
This is architecure dependent.
--- */
#if defined(CONFIG_ASM_I386)
#	define PI_CONTEXTSIZE		8
#	define PI_STACKDISPLACEMENT	0x100
#elif defined(CONFIG_ASM_SPARC)
#	define PI_CONTEXTSIZE		4
#	define PI_STACKDISPLACEMENT	0x100
#elif defined(CONFIG_ASM_MIPS)
#	define PI_CONTEXTSIZE		11
#	define PI_STACKDISPLACEMENT	0x100
#elif defined(CONFIG_ASM_HP)
#	define PI_CONTEXTSIZE		4
#	define PI_STACKDISPLACEMENT	0x100
#else
#	error Unsupported Machine Architecture
#endif

class UserLocalSemaphore;
class UserThread;
class ThreadScheduler;
class PollInfo;
class Poller;

int aUsedKeys[PI_MAXTHREADKEYS];			/* must be zero initialized */
static ThreadScheduler *___pLatentThreads = 0;	/* global thread scheduler */
static Poller *___pThePoller = 0;				/* polls on sockets/files */
static UserThread *___pTheMainThread = 0;		/* the main thread */
static UserThread *___pTheCurrentThread = 0;	/* the current thread */
#define ___refTheCurrentThread (UserThread *)___pTheCurrentThread)
static UserThread *___pNewThread = 0;			/* a newly created thread */
static UserThread *___pExitingThread = 0;		/* an exiting thread */
static int iThreadsCreated = 0;					/* since initialization */
extern "C" int StackContextSwitch(void);		/* most interesting function */
void DbgWriteAllThreads( ostream &os );			/* for debugging */

/*___________________________________________________________________________*\
 *
 Class:
 Description:
\*___________________________________________________________________________*/
class ThreadScheduler
{
private:
	DblList lThreads[PITHREAD_PRIORITY_SIZE];
	int iNumThreads;

	/* --- forbid copy constructor --- */
	ThreadScheduler( const ThreadScheduler & )
	:	iNumThreads( 0 )
		{ assert( 0 ); };

public:
	ThreadScheduler()
	:	iNumThreads( 0 )
		{};

	void AddThread( UserThread *pThread );

	/* ---
	Remove a latent thread from the list of threads, assumes
	that there is only one entry per thread
	--- */
	bool RemoveThread( UserThread *pThread )
		{
		for( int i=0; i<PITHREAD_PRIORITY_SIZE; i++)
			{
			DblList &tList = lThreads[i];
			for( DblListIterator j( tList ); !j.BadIndex(); j++)
				{
				if ( pThread == j.Current() )
					{	
					tList.Detach( j );
					iNumThreads--;
					RemoveThread( pThread );
					return true;
					};
				};
			};
		return false;
		}

	UserThread *SelectNextThread();
	UserThread *SelectNextRunnableThread( int iMandatory );
	bool ChangeThreadPriority( UserThread *pThread, int iOld, int iNew );
	void DbgWrite( ostream &os );
	inline int Size() const		{ return iNumThreads; };
};


// LATER
#if defined(CONFIG_OS_WIN16)
static WORD __wLastStackPos = 0;
#endif

/*___________________________________________________________________________*\
 *
 Class:
 Description:
\*___________________________________________________________________________*/
class UserThread : public Thread
{
public:
#if defined(CONFIG_CPP_EXCEPTIONS)
	class StackUnwindException
		{
		};
#else
	jmp_buf tJmpBuf;
#endif

private:
	void *aKeys[PI_MAXTHREADKEYS];	/* thread local data */
	int iThreadId;				/* thread identifier, for description */
	ThreadFn fnEntry;			/* user entry point for thread */
	unsigned long ulData;		/* data to the user entry point function */
	Allocator *pAllocator;		/* allocator for this thread */
	void *pStack;				/* the stack for this thread */
	unsigned long ulStatus;		/* final return code */
	int iPriority;				/* thread priority */
	bool bIsTerminated;			/* thread is dead */
	ThreadScheduler tWaiting;	/* threads waiting for this thread to die */
	int iStackSize;				/* size of stack to allocate */
	int iNextReturnCode;		/* result of a socket/file poll or sync. wait */

	/* --- runnable status (whether thread is blocked, and why) --- */
	UserLocalSemaphore *pSemaphore;		/* a semaphore we are waiting on */
	UserThread *pThread;				/* a thread we are waiting on to die */
	PollInfo *pPoll;					/* polling on socket/file, or asleep */
	bool bSuspended;					/* suspended */

	/* --- the thread context --- */ 
	size_t aContext[PI_CONTEXTSIZE];	/* for saving register context */

	/* --- put this thread to sleep, because of a semaphore --- */
	int PutToSleep( UserLocalSemaphore *pTheSemaphore )
		{
		assert( !pSemaphore );
		pSemaphore = pTheSemaphore;
		StackContextSwitch();
		int iTmp = iNextReturnCode;
		iNextReturnCode = 0;
		return iTmp;
		};

	/* --- put this thread to sleep, because of another thread --- */
	int PutToSleep( UserThread *pTheThread )
		{
		/* --- because we're waiting on another thread to die --- */
		assert( !pThread && pTheThread );
		pThread = pTheThread;
		pThread->tWaiting.AddThread( this );
		iNextReturnCode = 0;
		StackContextSwitch();
		int iTmp = iNextReturnCode;
		iNextReturnCode = 0;
		return iTmp;
		};

	/* --- put this thread to sleep, for no reason (suspend) --- */
	int PutToSleep()
		{
		StackContextSwitch();
		int iTmp = iNextReturnCode;
		iNextReturnCode = 0;
		return iTmp;
		};

	/* --- put this thread to sleep, because of socket poll --- */
	int PutToSleep( int iFD, int iFlags, int iTimeout );

	/* ---
	Force end of sleep, poll or wait, propably because of deadlock
	--- */
	void AbortBlocks( int iWhy );

 	/* --- make this thread runnable (or closer to runnable) --- */
	void MakeRunnable( UserLocalSemaphore *pTheSemaphore )
		{
		assert( pTheSemaphore==pSemaphore );
		pSemaphore = 0;
		};

	/* --- make this thread runnable (or closer to runnable) --- */
	void MakeRunnable( UserThread *pTheThread )
		{
		assert( pThread == pTheThread );
		pThread = 0;
		};

	/* --- make this thread runnable (or closer to...) --- */
	inline void MakeRunnable()
		{
		bSuspended = false;
		};

	/* --- make this thread runnable (or closer to runnable) --- */
	void MakeRunnable( int iThePollResult );

	void Cleanup();

	/* ---
	notification to this thread that a waiting thread is no longer
	waiting
	--- */
	void GaveUpWaiting( UserThread *pTheThread )
		{
		if ( !tWaiting.RemoveThread( pTheThread ) )
			{
			assert( 0 );		/* why did that thread notify us? */
			};
		};

	bool InternalSetPriority( int iThePriority );
	bool InternalTerminate( unsigned long ulTheStatus );

	/* --- forbid copy constructor --- */
	UserThread( const UserThread & )
	:	iThreadId( 0 ),
		fnEntry( 0 ),
		ulData( 0 ),
		pAllocator( 0 ),
		pStack( 0 ),
		ulStatus( 0UL ),	
		iPriority( PITHREAD_PRIORITY_MED ),
		bIsTerminated( true ),
		iStackSize( 0 ),		/* main thread has stack size=0 */
		iNextReturnCode( 0 ),
		pSemaphore( 0 ),	
		pThread( 0 ),
		pPoll( 0 ),
		bSuspended( false )
		{ assert( 0 ); };

public:
	UserThread( 
			Allocator *pTheAllocator = Platform::GetGlobalAllocator(),
			int iTheStackSize = PI_DEFAULTSTACKSIZE )
	:	iThreadId( iThreadsCreated++ ),
		fnEntry( 0 ),
		ulData( 0 ),
		pAllocator( pTheAllocator ),
		pStack( 0 ),
		ulStatus( 0UL ),	
		iPriority( PITHREAD_PRIORITY_MED ),
		bIsTerminated( true ),
		iStackSize( iTheStackSize ),	/* main thread has stack size=0 */
		iNextReturnCode( 0 ),
		pSemaphore( 0 ),	
		pThread( 0 ),
		pPoll( 0 ),
		bSuspended( false )
		{
#if DEBUG>=20
		CERR << "User Thread constructor: " << (void *)this << endl;
#endif
		if ( !pAllocator )
			{ return; };
		memset( aKeys, 0, sizeof( int ) * PI_MAXTHREADKEYS );
		if ( iStackSize )
			{
#	if !defined(CONFIG_OS_WIN16)
			pStack = Platform::AllocMemory( iStackSize );
#	else
			/*
			** Win16 - The segmented world!
			**
			** Allocate a stack for this thread from another part
			** of the main stack
			*/
			if ( __wLastStackPos==0 )
				{
				__wLastStackPos=(WORD)__Pi_GetCurrentStackPtr();
				};
			__wLastStackPos -= ( PI_DEFAULTSTACKSIZE );
			pStack = (void *)__wLastStackPos;
#	endif
			};
		};

	bool Begin( 
			ThreadFn fnTheEntry,
			unsigned long ulTheData, 
			int iThePriority,
			int iFlags )		
		{
#if DEBUG>=20
		CERR << "User Thread Begin(): " << (void *)this << endl;
		DbgWrite( CERR );
		CERR << endl;
#endif
		if ( !bIsTerminated )
			{
			PIERROR( PIAPI_EINVAL );
			return false;
			};
		if ( !fnTheEntry )
			{
			PIERROR( PIAPI_EINVAL );
			return false;
			};
		if ( iFlags & PITHREAD_FLAGS_SUSPENDED )
			{ bSuspended = true; };

		if ( this!=___pTheMainThread && !pStack )
			{
			PIERROR( PIAPI_EINVAL );
			return false;
			};
		/* --- reset these values --- */
		ulStatus = 0UL;
		bIsTerminated = false;
		fnEntry = fnTheEntry;
		ulData = ulTheData;
		InternalSetPriority( iThePriority );
		if ( pStack )
			{
			/* --- this is a regular thread --- */
			/* ---
			Set initial stack pointer assuming that the stack
			grows downwards
			--- */
#if defined(CONFIG_ASM_I386)
#	if defined(CONFIG_ASM_I386_WIN16)
			/* --- win 16 stack pointer is already setup */
			aContext[0] = ((size_t)pStack);
#	else
			aContext[0] = ((size_t)pStack) + ((size_t)iStackSize)
				- PI_STACKDISPLACEMENT;	// down
#	endif
#elif defined(CONFIG_ASM_SPARC)
			aContext[0] = ((size_t)pStack) + ((size_t)iStackSize)
				- PI_STACKDISPLACEMENT;	// down
#elif defined(CONFIG_ASM_MIPS)
			aContext[0] = ((size_t)pStack) + ((size_t)iStackSize)

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -