www.pudn.com > MessageQueue.zip > TaskMsg.c


/* 
Copyright (C) 2004  Liu Ge 
 
This program is free software; you can redistribute it and/or 
modify it under the terms of the GNU General Public License 
as published by the Free Software Foundation; either version 2 
of the License, or (at your option) any later version. 
 
This program is distributed in the hope that it will be useful, 
but WITHOUT ANY WARRANTY; without even the implied warranty of 
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the 
GNU General Public License for more details. 
 
You should have received a copy of the GNU General Public License 
along with this program; if not, write to the Free Software 
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA. 
 
*/ 
#include "msgqueue.h" 
#include "TaskMsg.h" 
 
static int s_iMsgThreadSlot; 
static int s_iMsgThreadProc; 
 
void MsgThread_Init(void) 
{ 
    s_iMsgThreadSlot = Thread_AllocSharedSlot(); 
    s_iMsgThreadProc = Thread_AllocSharedSlot(); 
} 
 
void MsgThread_Uninit(void) 
{ 
    Thread_FreeSharedSlot( s_iMsgThreadSlot ); 
    Thread_FreeSharedSlot( s_iMsgThreadProc ); 
} 
 
int MsgThread_Receive( void * pBuffer, int nLimit ) 
{ 
    P_MsgQueue pQueue; 
    int iCurrentThread = Thread_GetCurrentThreadId(); 
     
    if( Thread_GetSlot( iCurrentThread, s_iMsgThreadSlot, 
        (int *)&pQueue ) && 
        pQueue != NULL ) 
    { 
        return MsgQueue_Receive( pQueue, pBuffer, nLimit ); 
    } 
 
    return 0; 
} 
 
BOOL MsgThread_Send( int iThreadIdentifier, const void * pBuffer, int n ) 
{ 
    P_MsgQueue pQueue; 
 
    if( Thread_GetSlot( iThreadIdentifier, s_iMsgThreadSlot, 
        (int *)&pQueue ) && 
        pQueue != NULL ) 
    { 
        return MsgQueue_Send( pQueue, pBuffer, n ); 
    } 
     
    return FALSE; 
} 
 
static void  
ThreadDispatcher(void) 
{ 
    int iCurrentThread = Thread_GetCurrentThreadId(); 
    P_MsgQueue pQueue = MsgQueue_Create(); 
     
    if( pQueue != NULL ) 
    { 
        PFN_ThreadProc pfnThreadProc; 
 
        Thread_GetSlot(iCurrentThread, s_iMsgThreadProc, 
            (int *)&pfnThreadProc ); 
 
        Thread_SetSlot( iCurrentThread, s_iMsgThreadSlot, (int)pQueue ); 
 
        pfnThreadProc(); 
    } 
     
    MsgQueue_Destroy( pQueue ); 
} 
 
int MsgThread_Create( 
    PFN_ThreadProc pfnThreadProc,  
    BOOL isSuspended ) 
{ 
    int iThread = Thread_Create( ThreadDispatcher, FALSE ); 
     
    if( iThread != -1 ) 
    { 
        Thread_SetSlot( iThread, s_iMsgThreadProc, (int)pfnThreadProc ); 
        if( !isSuspended ) 
        { 
            Thread_Resume( iThread ); 
        } 
         
        return iThread; 
    } 
     
    return -1; 
}