(file) Return to Thread.h CVS log (file) (dir) Up to [Pegasus] / pegasus / src / Pegasus / Common

Diff for /pegasus/src/Pegasus/Common/Thread.h between version 1.11 and 1.57.2.3

version 1.11, 2002/03/31 00:37:56 version 1.57.2.3, 2006/07/29 01:03:42
Line 1 
Line 1 
 //%///////////-*-c++-*-//////////////////////////////////////////////////////  //%2006////////////////////////////////////////////////////////////////////////
 // //
 // Copyright (c) 2000, 2001 The Open group, BMC Software, Tivoli Systems, IBM  // Copyright (c) 2000, 2001, 2002 BMC Software; Hewlett-Packard Development
   // Company, L.P.; IBM Corp.; The Open Group; Tivoli Systems.
   // Copyright (c) 2003 BMC Software; Hewlett-Packard Development Company, L.P.;
   // IBM Corp.; EMC Corporation, The Open Group.
   // Copyright (c) 2004 BMC Software; Hewlett-Packard Development Company, L.P.;
   // IBM Corp.; EMC Corporation; VERITAS Software Corporation; The Open Group.
   // Copyright (c) 2005 Hewlett-Packard Development Company, L.P.; IBM Corp.;
   // EMC Corporation; VERITAS Software Corporation; The Open Group.
   // Copyright (c) 2006 Hewlett-Packard Development Company, L.P.; IBM Corp.;
   // EMC Corporation; Symantec Corporation; The Open Group.
 // //
 // Permission is hereby granted, free of charge, to any person obtaining a copy // Permission is hereby granted, free of charge, to any person obtaining a copy
 // of this software and associated documentation files (the "Software"), to // of this software and associated documentation files (the "Software"), to
Line 23 
Line 32 
 // Author: Mike Day (mdday@us.ibm.com) // Author: Mike Day (mdday@us.ibm.com)
 // //
 // Modified By: Markus Mueller // Modified By: Markus Mueller
   //              Roger Kumpf, Hewlett-Packard Company (roger_kumpf@hp.com)
   //              Amit K Arora, IBM (amita@in.ibm.com) for PEP#101
   //              David Dillard, VERITAS Software Corp.
   //                  (david.dillard@veritas.com)
   //              Sean Keenan, Hewlett-Packard Company (sean.keenan@hp.com)
   //              Josephine Eskaline Joyce, IBM (jojustin@in.ibm.com) for Bug#2393
 // //
 //%///////////////////////////////////////////////////////////////////////////// //%/////////////////////////////////////////////////////////////////////////////
  
   
 #ifndef Pegasus_Thread_h #ifndef Pegasus_Thread_h
 #define Pegasus_Thread_h #define Pegasus_Thread_h
   
   #include <cstring>
 #include <Pegasus/Common/Config.h> #include <Pegasus/Common/Config.h>
 #include <Pegasus/Common/IPC.h>  #include <Pegasus/Common/AtomicInt.h>
 #include <Pegasus/Common/Exception.h>  #include <Pegasus/Common/InternalException.h>
 #include <Pegasus/Common/DQueue.h>  #include <Pegasus/Common/AcceptLanguageList.h>
   #include <Pegasus/Common/Linkage.h>
   #include <Pegasus/Common/AutoPtr.h>
   #include <Pegasus/Common/List.h>
   #include <Pegasus/Common/Mutex.h>
   #include <Pegasus/Common/Semaphore.h>
   #include <Pegasus/Common/TSDKey.h>
   #include <Pegasus/Common/Threads.h>
  
 // REVIEW: Spend time getting to know this.  #if defined(PEGASUS_HAVE_PTHREADS)
   # include <signal.h>
   #endif
  
 PEGASUS_NAMESPACE_BEGIN PEGASUS_NAMESPACE_BEGIN
 PEGASUS_USING_STD;  
  
 class PEGASUS_COMMON_LINKAGE cleanup_handler  class PEGASUS_COMMON_LINKAGE cleanup_handler : public Linkable
 { {
  
    public:    public:
       cleanup_handler( void (*routine)(void *), void *arg  ) : _routine(routine), _arg(arg)  {}       cleanup_handler( void (*routine)(void *), void *arg  ) : _routine(routine), _arg(arg)  {}
       ~cleanup_handler()  {; }       ~cleanup_handler()  {; }
       inline Boolean operator==(const void *key) const  
       {  
          if(key == (void *)_routine)  
             return true;  
          return false;  
       }  
       inline Boolean operator ==(const cleanup_handler & b) const  
       {  
          return(operator==((const void *)b._routine));  
       }  
    private:    private:
       void execute(void) { _routine(_arg); }        void execute() { _routine(_arg); }
       cleanup_handler();       cleanup_handler();
       void (*_routine)(void *);       void (*_routine)(void *);
  
       void *_arg;       void *_arg;
       PEGASUS_CLEANUP_HANDLE _cleanup_buffer;  
       friend class DQueue<class cleanup_handler>;  
       friend class Thread;       friend class Thread;
 }; };
  
 /////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////
  
  
 class  PEGASUS_COMMON_LINKAGE thread_data  class  PEGASUS_COMMON_LINKAGE thread_data : public Linkable
 { {
  
    public:    public:
       static void default_delete(void *data);       static void default_delete(void *data);
  
       thread_data( const Sint8 *key ) : _delete_func(NULL) , _data(NULL), _size(0)        thread_data( const char *key ) : _delete_func(NULL) , _data(NULL), _size(0)
       {       {
          PEGASUS_ASSERT(key != NULL);          PEGASUS_ASSERT(key != NULL);
          size_t keysize = strlen(key);          size_t keysize = strlen(key);
          _key = new Sint8 [keysize + 1];           _key.reset(new char[keysize + 1]);
          memcpy(_key, key, keysize);           memcpy(_key.get(), key, keysize);
          _key[keysize] = 0x00;           _key.get()[keysize] = 0x00;
  
       }       }
  
       thread_data(const Sint8 *key, size_t size) : _delete_func(default_delete), _size(size)        thread_data(const char *key, size_t size) : _delete_func(default_delete), _size(size)
       {       {
          PEGASUS_ASSERT(key != NULL);          PEGASUS_ASSERT(key != NULL);
          size_t keysize = strlen(key);          size_t keysize = strlen(key);
          _key = new Sint8 [keysize + 1];           _key.reset(new char[keysize + 1]);
          memcpy(_key, key, keysize);           memcpy(_key.get(), key, keysize);
          _key[keysize] = 0x00;           _key.get()[keysize] = 0x00;
          _data = ::operator new(_size) ;          _data = ::operator new(_size) ;
  
       }       }
  
       thread_data(const Sint8 *key, size_t size, void *data) : _delete_func(default_delete), _size(size)        thread_data(const char *key, size_t size, void *data) : _delete_func(default_delete), _size(size)
       {       {
          PEGASUS_ASSERT(key != NULL);          PEGASUS_ASSERT(key != NULL);
          PEGASUS_ASSERT(data != NULL);          PEGASUS_ASSERT(data != NULL);
          size_t keysize = strlen(key);          size_t keysize = strlen(key);
  
          _key = new Sint8[keysize + 1];           _key.reset(new char[keysize + 1]);
          memcpy(_key, key, keysize);           memcpy(_key.get(), key, keysize);
          _key[keysize] = 0x00;           _key.get()[keysize] = 0x00;
          _data = ::operator new(_size);          _data = ::operator new(_size);
          memcpy(_data, data, size);          memcpy(_data, data, size);
       }       }
Line 116 
Line 129 
             {             {
                _delete_func( _data );                _delete_func( _data );
             }             }
          if( _key != NULL )  
             delete [] _key;  
       }       }
  
       void put_data(void (*del)(void *), size_t size, void *data ) throw(NullPointer)        /**
          * This function is used to put data in thread space.
          *
          * Be aware that there is NOTHING in place to stop
          * other users of the thread to remove this data.
          * Or change the data.
          *
          * You, the developer has to make sure that there are
          * no situations in which this can arise (ie, have a
          * lock for the function which manipulates the TSD.
          *
          * @exception NullPointer
          */
         void put_data(void (*del)(void *), size_t size, void *data )
       {       {
          if(_data != NULL)          if(_data != NULL)
             if(_delete_func != NULL)             if(_delete_func != NULL)
Line 132 
Line 156 
          return ;          return ;
       }       }
  
       size_t get_size(void) { return _size; }        size_t get_size() { return _size; }
  
         /**
          * This function is used to retrieve data from the
          * TSD, the thread specific data.
          *
          * Be aware that there is NOTHING in place to stop
          * other users of the thread to change the data you
          * get from this function.
          *
          * You, the developer has to make sure that there are
          * no situations in which this can arise (ie, have a
          * lock for the function which manipulates the TSD.
          */
       void get_data(void **data, size_t *size)       void get_data(void **data, size_t *size)
       {       {
          if(data == NULL || size == NULL)          if(data == NULL || size == NULL)
Line 145 
Line 181 
  
       }       }
  
       void copy_data(void **buf, size_t *size) throw(BufferTooSmall, NullPointer)        // @exception NullPointer
         void copy_data(void **buf, size_t *size)
       {       {
          if((buf == NULL) || (size == NULL))          if((buf == NULL) || (size == NULL))
             throw NullPointer() ;             throw NullPointer() ;
Line 157 
Line 194 
  
       inline Boolean operator==(const void *key) const       inline Boolean operator==(const void *key) const
       {       {
          if ( ! strcmp(_key, (Sint8 *)key))           if ( ! strcmp(_key.get(), reinterpret_cast<const char *>(key)))
             return(true);             return(true);
          return(false);          return(false);
       }       }
  
       inline Boolean operator==(const thread_data& b) const       inline Boolean operator==(const thread_data& b) const
       {       {
          return(operator==((const void *)b._key));           return(operator==(b._key.get()));
         }
   
         static bool equal(const thread_data* node, const void* key)
         {
            return ((thread_data*)node)->operator==(key);
       }       }
  
    private:    private:
Line 172 
Line 214 
       thread_data();       thread_data();
       void *_data;       void *_data;
       size_t _size;       size_t _size;
       Sint8 *_key;        AutoArrayPtr<char> _key;
  
       friend class DQueue<thread_data>;  
       friend class Thread;       friend class Thread;
 }; };
  
  
 ///////////////////////////////////////////////////////////////////////////  enum ThreadStatus {
           PEGASUS_THREAD_OK = 1, /* No problems */
           PEGASUS_THREAD_INSUFFICIENT_RESOURCES, /* Can't allocate a thread. Not enough
                                           memory. Try again later */
           PEGASUS_THREAD_SETUP_FAILURE, /* Could not allocate into the thread specific
                                    data storage. */
           PEGASUS_THREAD_UNAVAILABLE  /* Service is being destroyed and no new threads can
                                  be provided. */
   };
  
 class PEGASUS_COMMON_LINKAGE ThreadPool;  ///////////////////////////////////////////////////////////////////////////
  
 class PEGASUS_COMMON_LINKAGE Thread  class PEGASUS_COMMON_LINKAGE Thread : public Linkable
 { {
   
    public:    public:
       Thread( PEGASUS_THREAD_RETURN (PEGASUS_THREAD_CDECL *start )(void *),  
         Thread( ThreadReturnType (PEGASUS_THREAD_CDECL *start )(void *),
               void *parameter, Boolean detached );               void *parameter, Boolean detached );
  
       ~Thread();       ~Thread();
  
       void run(void);        /**
             Start the thread.
             @return PEGASUS_THREAD_OK if the thread is started successfully,
                     PEGASUS_THREAD_INSUFFICIENT_RESOURCES if the resources necessary
                     to start the thread are not currently available.
                     PEGASUS_THREAD_SETUP_FAILURE if the thread could not
                     be create properly - check the 'errno' value for specific operating
                     system return code.
          */
         ThreadStatus run();
  
       // get the user parameter       // get the user parameter
       inline void *get_parm(void) { return _thread_parm; }        inline void *get_parm() { return _thread_parm; }
   
       // send the thread a signal -- may not be appropriate due to Windows  
       //  void kill(int signum);  
  
       // cancellation must be deferred (not asynchronous)       // cancellation must be deferred (not asynchronous)
       // for user-level threads the thread itself can decide       // for user-level threads the thread itself can decide
       // when it should die.       // when it should die.
       void cancel(void);        void cancel();
  
       // cancel if there is a pending cancellation request       // cancel if there is a pending cancellation request
       void test_cancel(void);        void test_cancel();
  
       Boolean is_cancelled(void);        Boolean is_cancelled();
  
       // for user-level threads  - put the calling thread       // for user-level threads  - put the calling thread
       // to sleep and jump to the thread scheduler.       // to sleep and jump to the thread scheduler.
Line 218 
Line 273 
       // or gnu portable threads will have an existing       // or gnu portable threads will have an existing
       // routine that can be mapped to this method       // routine that can be mapped to this method
  
       void thread_switch(void);        void thread_switch();
  
 #if defined(PEGASUS_PLATFORM_LINUX_IX86_GNU) || defined(PEGASUS_PLATFORM_LINUX_GENERIC_GNU)  #if defined(PEGASUS_PLATFORM_LINUX_GENERIC_GNU)
       // suspend this thread       // suspend this thread
       void suspend(void) ;        void suspend();
  
       // resume this thread       // resume this thread
       void resume(void) ;        void resume();
 #endif #endif
  
       static void sleep(Uint32 msec) ;       static void sleep(Uint32 msec) ;
  
       // block the calling thread until this thread terminates       // block the calling thread until this thread terminates
       void join( void );        void join();
       void thread_init(void);        void thread_init();
  
       // thread routine needs to call this function when       // thread routine needs to call this function when
       // it is ready to exit       // it is ready to exit
       void exit_self(PEGASUS_THREAD_RETURN return_code) ;        void exit_self(ThreadReturnType return_code);
  
       // stack of functions to be called when thread terminates       // stack of functions to be called when thread terminates
       // will be called last in first out (LIFO)       // will be called last in first out (LIFO)
       void cleanup_push( void (*routine) (void *), void *parm ) throw(IPCException);        // @exception IPCException
       void cleanup_pop(Boolean execute = true) throw(IPCException);        void cleanup_push(void (*routine) (void *), void *parm);
   
         // @exception IPCException
         void cleanup_pop(Boolean execute = true);
  
       // create and initialize a tsd       // create and initialize a tsd
       inline void create_tsd(const Sint8 *key, int size, void *buffer) throw(IPCException)        // @exception IPCException
         inline void create_tsd(const char *key, int size, void *buffer)
       {       {
          thread_data *tsd = new thread_data(key, size, buffer);          AutoPtr<thread_data> tsd(new thread_data(key, size, buffer));
          try { _tsd.insert_first(tsd); }          _tsd.insert_front(tsd.get());
          catch(IPCException& e) { e = e; delete tsd; throw; }          tsd.release();
       }       }
  
       // get the buffer associated with the key       // get the buffer associated with the key
       // NOTE: this call leaves the tsd LOCKED !!!!       // NOTE: this call leaves the tsd LOCKED !!!!
       inline void *reference_tsd(const Sint8 *key) throw(IPCException)        // @exception IPCException
         inline void *reference_tsd(const char *key)
       {       {
          _tsd.lock();          _tsd.lock();
          thread_data *tsd = _tsd.reference((const void *)key);           thread_data *tsd = _tsd.find(thread_data::equal, key);
          if(tsd != NULL)          if(tsd != NULL)
             return( (void *)(tsd->_data) );             return( (void *)(tsd->_data) );
          else          else
             return(NULL);             return(NULL);
       }       }
  
       inline void *try_reference_tsd(const Sint8 *key) throw(IPCException)        // @exception IPCException
         inline void *try_reference_tsd(const char *key)
       {       {
          _tsd.try_lock();          _tsd.try_lock();
          thread_data *tsd = _tsd.reference((const void *)key);           thread_data *tsd = _tsd.find(thread_data::equal, key);
          if(tsd != NULL)          if(tsd != NULL)
             return((void *)(tsd->_data) );             return((void *)(tsd->_data) );
          else          else
Line 276 
Line 337 
  
       // release the lock held on the tsd       // release the lock held on the tsd
       // NOTE: assumes a corresponding and prior call to reference_tsd() !!!       // NOTE: assumes a corresponding and prior call to reference_tsd() !!!
       inline void dereference_tsd(void) throw(IPCException)        // @exception IPCException
         inline void dereference_tsd()
       {       {
          _tsd.unlock();          _tsd.unlock();
       }       }
  
       // delete the tsd associated with the key       // delete the tsd associated with the key
       inline void delete_tsd(const Sint8 *key) throw(IPCException)        // @exception IPCException
       {        inline void delete_tsd(const char *key)
          thread_data *tsd = _tsd.remove((const void *)key);  
          if(tsd != NULL)  
             delete tsd;  
       }  
   
       inline void *remove_tsd(const Sint8 *key) throw(IPCException)  
       {       {
          return(_tsd.remove((const void *)key));           AutoPtr<thread_data> tsd(_tsd.remove(thread_data::equal, key));
       }       }
  
       inline void empty_tsd(void) throw(IPCException)        // @exception IPCException
         inline void empty_tsd()
       {       {
          _tsd.empty_list();           _tsd.clear();
       }       }
  
       // create or re-initialize tsd associated with the key       // create or re-initialize tsd associated with the key
       // if the tsd already exists, return the existing buffer        // if the tsd already exists, delete the existing buffer
       thread_data *put_tsd(const Sint8 *key, void (*delete_func)(void *), Uint32 size, void *value)        // @exception IPCException
          throw(IPCException)        void put_tsd(const char *key, void (*delete_func)(void *), Uint32 size, void *value)
   
       {       {
          PEGASUS_ASSERT(key != NULL);          PEGASUS_ASSERT(key != NULL);
          thread_data *tsd ;           AutoPtr<thread_data> tsd;
          tsd = _tsd.remove((const void *)key);  // may throw an IPC exception           tsd.reset(_tsd.remove(thread_data::equal, key));  // may throw an IPC exception
          thread_data *ntsd = new thread_data(key);           tsd.reset();
            AutoPtr<thread_data> ntsd(new thread_data(key));
          ntsd->put_data(delete_func, size, value);          ntsd->put_data(delete_func, size, value);
          try { _tsd.insert_first(ntsd); }           try { _tsd.insert_front(ntsd.get()); }
          catch(IPCException& e) { e = e; delete ntsd; throw; }           catch(IPCException& e) { e = e; throw; }
          return(tsd);           ntsd.release();
       }       }
       inline PEGASUS_THREAD_RETURN get_exit(void) { return _exit_code; }        inline ThreadReturnType get_exit() { return _exit_code; }
       inline PEGASUS_THREAD_TYPE self(void) {return pegasus_thread_self(); }        inline ThreadType self() {return Threads::self(); }
  
       PEGASUS_THREAD_HANDLE getThreadHandle() {return _handle;}        ThreadHandle getThreadHandle() {return _handle;}
  
       inline Boolean operator==(const void *key) const        void detach();
       {  
          if ( (void *)this == key)        //
             return(true);        //  Gets the Thread object associated with the caller's thread.
          return(false);        //  Note: this may return NULL if no Thread object is associated
       }        //  with the caller's thread.
       inline Boolean operator==(const Thread & b) const        //
       {        static Thread * getCurrent();  // l10n
          return(operator==((const void *)&b ));  
       }        //
         //  Sets the Thread object associated with the caller's thread.
         //  Note: the Thread object must be placed on the heap.
         //
         static void setCurrent(Thread * thrd); // l10n
   
         //
         //  Gets the AcceptLanguageList object associated with the caller's
         //  Thread.
         //  Note: this may return NULL if no Thread object, or no
         //  AcceptLanguageList object, is associated with the caller's thread.
         //
         static AcceptLanguageList * getLanguages(); //l10n
  
       void detach(void);        //
         //  Sets the AcceptLanguageList object associated with the caller's
         //  Thread.
         //  Note: a Thread object must have been previously associated with
         //  the caller's thread.
         //  Note: the AcceptLanguageList object must be placed on the heap.
         //
         static void setLanguages(AcceptLanguageList *langs); //l10n
   
         //
         //  Removes the AcceptLanguageList object associated with the caller's
         //  Thread.
         //
         static void clearLanguages(); //l10n
  
    private:    private:
       Thread();       Thread();
       inline void create_tsd(const Sint8 *key ) throw(IPCException)  
         static Sint8 initializeKey();  // l10n
   
         // @exception IPCException
         inline void create_tsd(const char *key )
       {       {
          thread_data *tsd = new thread_data(key);           AutoPtr<thread_data> tsd(new thread_data(key));
          try { _tsd.insert_first(tsd); }           _tsd.insert_front(tsd.get());
          catch(IPCException& e) { e = e; delete tsd; throw; }           tsd.release();
       }       }
       PEGASUS_THREAD_HANDLE _handle;        ThreadHandle _handle;
       Boolean _is_detached;       Boolean _is_detached;
       Boolean _cancel_enabled;       Boolean _cancel_enabled;
       Boolean _cancelled;       Boolean _cancelled;
  
       PEGASUS_SEM_HANDLE _suspend_count;  
   
       // always pass this * as the void * parameter to the thread       // always pass this * as the void * parameter to the thread
       // store the user parameter in _thread_parm       // store the user parameter in _thread_parm
  
       PEGASUS_THREAD_RETURN  ( PEGASUS_THREAD_CDECL *_start)(void *) ;        ThreadReturnType  ( PEGASUS_THREAD_CDECL *_start)(void *);
       DQueue<class cleanup_handler> _cleanup;        List<cleanup_handler, Mutex> _cleanup;
       DQueue<class thread_data> _tsd;        List<thread_data, Mutex> _tsd;
  
       void *_thread_parm;       void *_thread_parm;
       PEGASUS_THREAD_RETURN _exit_code;        ThreadReturnType _exit_code;
       static Boolean _signals_blocked;       static Boolean _signals_blocked;
       friend class ThreadPool;        static TSDKeyType _platform_thread_key;  //l10n
         static Boolean _key_initialized; // l10n
         static Boolean _key_error; // l10n
 } ; } ;
  
  
Line 365 
Line 451 
 { {
    public:    public:
  
       ThreadPool(Sint16 initial_size,      /**
                  const Sint8 *key,          Constructs a new ThreadPool object.
                  Sint16 min,          @param initialSize The number of threads that are initially added to
                  Sint16 max,              the thread pool.
                  struct timeval & alloc_wait,          @param key A name for this thread pool that can be used to determine
                  struct timeval & dealloc_wait,              equality of two thread pool objects.  Only the first 16 characters
                  struct timeval & deadlock_detect);              of this value are used.
           @param minThreads The minimum number of threads that should be
       ~ThreadPool(void);              contained in this thread pool at any given time.
           @param maxThreads The maximum number of threads that should be
       void allocate_and_awaken(void *parm,              contained in this thread pool at any given time.
                                PEGASUS_THREAD_RETURN (PEGASUS_THREAD_CDECL *work)(void *),          @param deallocateWait The minimum time that a thread should be idle
                                Semaphore *blocking = 0)              before it is removed from the pool and cleaned up.
          throw(IPCException);       */
       ThreadPool(
           Sint16 initialSize,
           const char* key,
           Sint16 minThreads,
           Sint16 maxThreads,
           struct timeval& deallocateWait);
   
       /**
           Destructs the ThreadPool object.
        */
       ~ThreadPool();
   
       /**
           Allocate and start a thread to do a unit of work.
           @param parm A generic parameter to pass to the thread
           @param work A pointer to the function that is to be executed by
                       the thread
           @param blocking A pointer to an optional semaphore which, if
                           specified, is signaled after the thread finishes
                           executing the work function
           @return PEGASUS_THREAD_OK if the thread is started successfully,
                   PEGASUS_THREAD_INSUFFICIENT_RESOURCES  if the
                   resources necessary to start the thread are not currently
                   available.  PEGASUS_THREAD_SETUP_FAILURE if the thread
                   could not be setup properly. PEGASUS_THREAD_UNAVAILABLE
                   if this service is shutting down and no more threads can
                   be allocated.
           @exception IPCException
        */
       ThreadStatus allocate_and_awaken(
           void* parm,
           ThreadReturnType (PEGASUS_THREAD_CDECL* work)(void *),
           Semaphore* blocking = 0);
   
       /**
           Cleans up idle threads if they have been running longer than the
           deallocate_wait configuration and more than the configured
           minimum number of threads is running.
           @return The number of threads that were cleaned up.
           @exception IPCException
        */
       Uint32 cleanupIdleThreads();
  
       void get_key(Sint8* buf, int bufsize);
  
       Uint32 kill_dead_threads( void )      inline void setMinThreads(Sint16 min)
          throw(IPCException);      {
           _minThreads = min;
       }
  
       void get_key(Sint8 *buf, int bufsize);      inline Sint16 getMinThreads() const
       {
           return _minThreads;
       }
  
       inline Boolean operator==(const void *key) const      inline void setMaxThreads(Sint16 max)
       {       {
          if ( ! strncmp( reinterpret_cast<Sint8 *>(const_cast<void *>(key)), _key, 16  ))          _maxThreads = max;
             return(true);      }
          return(false);  
       inline Sint16 getMaxThreads() const
       {
           return _maxThreads;
       }       }
       inline Boolean operator==(const ThreadPool & b) const  
       inline Uint32 runningCount()
       {       {
          return(operator==((const void *) b._key ));          return _runningThreads.size();
       }       }
  
       inline void set_min_threads(Sint16 min)      inline Uint32 idleCount()
       {       {
          _min_threads = min;          return _idleThreads.size();
       }       }
  
       inline Sint16 get_min_threads(void) const  private:
   
       ThreadPool();    // Unimplemented
       ThreadPool(const ThreadPool&);    // Unimplemented
       ThreadPool& operator=(const ThreadPool&);    // Unimplemented
   
       static ThreadReturnType PEGASUS_THREAD_CDECL _loop(void *);
   
       static Boolean _timeIntervalExpired(
           struct timeval* start,
           struct timeval* interval);
   
       static void _deleteSemaphore(void* p);
   
       void _cleanupThread(Thread* thread);
       Thread* _initializeThread();
       void _addToIdleThreadsQueue(Thread* th);
   
       Sint16 _maxThreads;
       Sint16 _minThreads;
       AtomicInt _currentThreads;
       struct timeval _deallocateWait;
       char _key[17];
       List<Thread, Mutex> _idleThreads;
       List<Thread, Mutex> _runningThreads;
       AtomicInt _dying;
   };
   
   //==============================================================================
   //
   // POSIX Threads Implementation:
   //
   //==============================================================================
   
   #if defined(PEGASUS_HAVE_PTHREADS)
   
   struct StartWrapperArg
   {
       void* (PEGASUS_THREAD_CDECL* start)(void*);
       void* arg;
   };
   
   extern "C" void* _start_wrapper(void* arg);
   
   inline ThreadStatus Thread::run()
   {
       StartWrapperArg* arg = new StartWrapperArg;
       arg->start = _start;
       arg->arg = this;
   
       Threads::Type type = _is_detached ? Threads::DETACHED : Threads::JOINABLE;
       int rc = Threads::create(_handle.thid, type, _start_wrapper, arg);
   
       // On Linux distributions released prior 2005, the implementation of
       // Native POSIX Thread Library returns ENOMEM instead of EAGAIN when there
       // are no insufficient memory.  Hence we are checking for both.  See bug
       // 386.
   
       if ((rc == EAGAIN) || (rc == ENOMEM))
       {       {
          return _min_threads;          Threads::clear(_handle.thid);
           delete arg;
           return PEGASUS_THREAD_INSUFFICIENT_RESOURCES;
       }
       else if (rc != 0)
       {
           Threads::clear(_handle.thid);
           delete arg;
           return PEGASUS_THREAD_SETUP_FAILURE;
       }
       return PEGASUS_THREAD_OK;
       }       }
  
       inline void set_max_threads(Sint16 max)  inline void Thread::cancel()
       {       {
          _max_threads = max;      _cancelled = true;
       pthread_cancel(_handle.thid.tt_handle());
       }       }
  
       inline Sint16 get_max_threads(void) const  inline void Thread::test_cancel()
       {       {
          return _max_threads;  #if defined(PEGASUS_PLATFORM_ZOS_ZSERIES_IBM)
       pthread_testintr();
   #else
       pthread_testcancel();
   #endif
       }       }
  
       inline void set_allocate_wait(const struct timeval & alloc_wait)  inline Boolean Thread::is_cancelled(void)
       {       {
          _allocate_wait.tv_sec = alloc_wait.tv_sec;     return _cancelled;
          _allocate_wait.tv_usec = alloc_wait.tv_usec;  
       }       }
  
       inline struct timeval *get_allocate_wait(struct timeval *buffer) const  inline void Thread::thread_switch()
       {       {
          if(buffer == 0)  #if defined(PEGASUS_PLATFORM_ZOS_ZSERIES_IBM)
             throw NullPointer();      pthread_yield(NULL);
          buffer->tv_sec = _allocate_wait.tv_sec;  #else
          buffer->tv_usec = _allocate_wait.tv_usec;      sched_yield();
          return buffer;  #endif
       }       }
  
       inline void set_deallocate_wait(const struct timeval & dealloc_wait)  /*
   ATTN: why are these missing on other platforms?
   */
   #if defined(PEGASUS_PLATFORM_LINUX_GENERIC_GNU)
   inline void Thread::suspend()
       {       {
          _deallocate_wait.tv_sec = dealloc_wait.tv_sec;      pthread_kill(_handle.thid.tt_handle(),SIGSTOP);
          _deallocate_wait.tv_usec = dealloc_wait.tv_usec;  
       }       }
  
       inline struct timeval *get_deallocate_wait(struct timeval *buffer) const  inline void Thread::resume()
       {       {
          if(buffer == 0)      pthread_kill(_handle.thid.tt_handle(),SIGCONT);
             throw NullPointer();  
          buffer->tv_sec = _deallocate_wait.tv_sec;  
          buffer->tv_usec = _deallocate_wait.tv_usec;  
          return buffer;  
       }       }
   #endif
  
       inline void set_deadlock_detect(const struct timeval & deadlock)  inline void Thread::sleep(Uint32 msec)
       {       {
          _deadlock_detect.tv_sec = deadlock.tv_sec;      Threads::sleep(msec);
          _deadlock_detect.tv_usec = deadlock.tv_usec;  
       }       }
  
       inline struct timeval * get_deadlock_detect(struct timeval *buffer) const  inline void Thread::join(void)
       {       {
          if(buffer == 0)      if (!_is_detached && Threads::id(_handle.thid) != 0)
             throw NullPointer();          pthread_join(_handle.thid.tt_handle(), &_exit_code);
          buffer->tv_sec = _deadlock_detect.tv_sec;  
          buffer->tv_usec = _deadlock_detect.tv_usec;      Threads::clear(_handle.thid);
          return buffer;  
       }       }
  
       inline Uint32 running_count(void)  inline void Thread::thread_init(void)
       {       {
          return _running.count();  #if defined(PEGASUS_PLATFORM_ZOS_ZSERIES_IBM)
       pthread_setintr(PTHREAD_INTR_ENABLE);
       pthread_setintrtype(PTHREAD_INTR_ASYNCHRONOUS);
   #else
       pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL);
       pthread_setcanceltype(PTHREAD_CANCEL_DEFERRED, NULL);
   #endif
       _cancel_enabled = true;
       }       }
  
       static Boolean check_time(struct timeval *start, struct timeval *interval);  inline void Thread::detach(void)
   {
      _is_detached = true;
      pthread_detach(_handle.thid.tt_handle());
   }
  
    private:  #endif /* PEGASUS_HAVE_PTHREADS */
       ThreadPool(void);  
       Sint16 _max_threads;  
       Sint16 _min_threads;  
       AtomicInt _current_threads;  
       struct timeval _allocate_wait;  
       struct timeval _deallocate_wait;  
       struct timeval _deadlock_detect;  
       static PEGASUS_THREAD_RETURN PEGASUS_THREAD_CDECL _loop(void *);  
       Sint8 _key[17];  
       DQueue<Thread> _pool;  
       DQueue<Thread> _running;  
       DQueue<Thread> _dead;  
       AtomicInt _dying;  
  
   //==============================================================================
   //
   // Windows Threads Implementation:
   //
   //==============================================================================
  
       static void _sleep_sem_del(void *p);  #if defined(PEGASUS_HAVE_WINDOWS_THREADS)
  
       void _check_deadlock(struct timeval *start) throw(Deadlock);  inline ThreadStatus Thread::run(void)
       Boolean _check_deadlock_no_throw(struct timeval *start);  {
       Boolean _check_dealloc(struct timeval *start);      // Note: A Win32 thread ID is not the same thing as a pthread ID.
       Thread *_init_thread(void) throw(IPCException);      // Win32 threads have both a thread ID and a handle.  The handle
       void _link_pool(Thread *th) throw(IPCException);      // is used in the wait functions, etc.
       static PEGASUS_THREAD_RETURN  _undertaker(void *);      // So _handle.thid is actually the thread handle.
  
  };      unsigned threadid = 0;
  
       ThreadType tt;
       tt.handle = (HANDLE)_beginthreadex(NULL, 0, _start, this, 0, &threadid);
       _handle.thid = tt;
  
 inline void ThreadPool::_sleep_sem_del(void *p)      if (Threads::id(_handle.thid) == 0)
       {
           if (errno == EAGAIN)
 { {
    if(p != 0)              return PEGASUS_THREAD_INSUFFICIENT_RESOURCES;
           }
           else
    {    {
       delete (Semaphore *)p;              return PEGASUS_THREAD_SETUP_FAILURE;
    }    }
 } }
       return PEGASUS_THREAD_OK;
   }
  
 inline void ThreadPool::_check_deadlock(struct timeval *start) throw(Deadlock)  inline void Thread::cancel(void)
 { {
    if (true == check_time(start, &_deadlock_detect))          _cancelled = true;
       throw Deadlock(pegasus_thread_self());  }
    return;  
   inline void Thread::test_cancel(void)
   {
           if( _cancel_enabled && _cancelled )
           {
                   exit_self( 0 );
           }
 } }
  
   inline Boolean Thread::is_cancelled(void)
   {
           return _cancelled;
   }
  
 inline Boolean ThreadPool::_check_deadlock_no_throw(struct timeval *start)  inline void Thread::thread_switch(void)
 { {
    return(check_time(start, &_deadlock_detect));          Sleep( 0 );
 } }
  
 inline Boolean ThreadPool::_check_dealloc(struct timeval *start)  inline void Thread::sleep( Uint32 milliseconds )
 { {
    return(check_time(start, &_deallocate_wait));          Sleep( milliseconds );
 } }
  
 inline Thread *ThreadPool::_init_thread(void) throw(IPCException)  inline void Thread::join(void)
   {
           if( Threads::id(_handle.thid) != 0 )
           {
                   if( !_is_detached )
                   {
                           if( !_cancelled )
                           {
                                   // Emulate the unix join api. Caller sleeps until thread is done.
                                   WaitForSingleObject( _handle.thid.handle, INFINITE );
                           }
                           else
                           {
                                   // Currently this is the only way to ensure this code does not
                                   // hang forever.
                                   if( WaitForSingleObject( _handle.thid.handle, 10000 ) == WAIT_TIMEOUT )
 { {
    Thread *th = (Thread *) new Thread(_loop, this, false);                                          TerminateThread( _handle.thid.handle, 0 );
    // allocate a sleep semaphore and pass it in the thread context                                  }
    // initial count is zero, loop function will sleep until                          }
    // we signal the semaphore  
    Semaphore *sleep_sem = (Semaphore *) new Semaphore(0);  
    th->put_tsd("sleep sem", &_sleep_sem_del, sizeof(Semaphore), (void *)sleep_sem);  
  
    struct timeval *dldt = (struct timeval *) ::operator new(sizeof(struct timeval));                          DWORD exit_code = 0;
    th->put_tsd("deadlock timer", thread_data::default_delete, sizeof(struct timeval), (void *)dldt);                          GetExitCodeThread( _handle.thid.handle, &exit_code );
    // thread will enter _loop(void *) and sleep on sleep_sem until we signal it                          _exit_code = (ThreadReturnType)exit_code;
    th->run();                  }
    _current_threads++;  
    pegasus_yield();  
  
    return th;                  CloseHandle( _handle.thid.handle );
                   Threads::clear(_handle.thid);
           }
 } }
  
 inline void ThreadPool::_link_pool(Thread *th) throw(IPCException)  inline void Thread::thread_init(void)
 { {
    if(th == 0)          _cancel_enabled = true;
       throw NullPointer();  
    _pool.insert_first(th);  
 } }
  
   inline void Thread::detach(void)
   {
           _is_detached = true;
   }
  
 #if defined(PEGASUS_OS_TYPE_WINDOWS)  #endif /* PEGASUS_HAVE_WINDOWS_THREADS */
 # include "ThreadWindows_inline.h"  
 #elif defined(PEGASUS_PLATFORM_ZOS_ZSERIES_IBM)  
 # include "ThreadzOS_inline.h"  
 #elif defined(PEGASUS_OS_TYPE_UNIX)  
 # include "ThreadUnix_inline.h"  
 #endif  
  
 PEGASUS_NAMESPACE_END PEGASUS_NAMESPACE_END
  


Legend:
Removed from v.1.11  
changed lines
  Added in v.1.57.2.3

No CVS admin address has been configured
Powered by
ViewCVS 0.9.2