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

Diff for /pegasus/src/Pegasus/Common/Thread.cpp between version 1.1.2.13 and 1.107

version 1.1.2.13, 2001/11/12 16:52:57 version 1.107, 2008/09/16 18:37:03
Line 1 
Line 1 
   //%2006////////////////////////////////////////////////////////////////////////
 //%/////////////////////////////////////////////////////////////////////////////  
 // //
 // Copyright (c) 2000, 2001 The Open group, BMC Software, Tivoli Systems, IBM,  // Copyright (c) 2000, 2001, 2002 BMC Software; Hewlett-Packard Development
 // Compaq Computer Corporation  // 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 22 
Line 29 
 // //
 //============================================================================== //==============================================================================
 // //
 // Author: Mike Day (mdday@us.ibm.com)  
 //  
 // Modified By: Rudy Schuet (rudy.schuet@compaq.com) 11/12/01  
 //              added nsk platform support  
 //  
 //%///////////////////////////////////////////////////////////////////////////// //%/////////////////////////////////////////////////////////////////////////////
  
 #include "Thread.h" #include "Thread.h"
 #include <Pegasus/Common/IPC.h>  #include <errno.h>
   #include <exception>
   #include <Pegasus/Common/Tracer.h>
   #include <Pegasus/Common/AutoPtr.h>
   #include "Time.h"
   
   PEGASUS_USING_STD;
   
   PEGASUS_NAMESPACE_BEGIN
   
   //==============================================================================
   //
   // 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_)
   {
       // Clean up dynamic memory now to prevent a leak if the thread is canceled.
       StartWrapperArg arg;
       arg.start = ((StartWrapperArg *) arg_)->start;
       arg.arg = ((StartWrapperArg *) arg_)->arg;
       delete (StartWrapperArg *) arg_;
   
       // establish cancelability of the thread
       pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL);
       pthread_setcanceltype(PTHREAD_CANCEL_DEFERRED, NULL);
   
       void *return_value = (*arg.start) (arg.arg);
   
       return return_value;
   }
  
 #if defined(PEGASUS_OS_TYPE_WINDOWS)  void Thread::cancel()
 # include "ThreadWindows.cpp"  {
 #elif defined(PEGASUS_OS_TYPE_UNIX)      pthread_cancel(_handle.thid.thread);
 # include "ThreadUnix.cpp"  }
 #elif defined(PEGASUS_OS_TYPE_NSK)  
 # include "ThreadNsk.cpp"  void Thread::thread_switch()
   {
   #if defined(PEGASUS_PLATFORM_ZOS_ZSERIES_IBM)
       pthread_yield(NULL);
 #else #else
 # error "Unsupported platform"      sched_yield();
 #endif #endif
   }
  
 PEGASUS_NAMESPACE_BEGIN  void Thread::sleep(Uint32 msec)
   {
       Threads::sleep(msec);
   }
  
 void thread_data::default_delete(void * data)  void Thread::join()
 { {
    if( data != NULL)      if (!_is_detached && !Threads::null(_handle.thid))
       ::operator delete(data);          pthread_join(_handle.thid.thread, &_exit_code);
   
       Threads::clear(_handle.thid);
 } }
  
 Boolean Thread::_signals_blocked = false;  void Thread::detach()
   {
       _is_detached = true;
   #if defined(PEGASUS_PLATFORM_ZOS_ZSERIES_IBM)
       pthread_t  thread_id=_handle.thid.thread;
       pthread_detach(&thread_id);
   #else
       pthread_detach(_handle.thid.thread);
   #endif
   }
  
 // for non-native implementations  ThreadStatus Thread::run()
 #ifndef PEGASUS_THREAD_CLEANUP_NATIVE  
 void Thread::cleanup_push( void (*routine)(void *), void *parm) throw(IPCException)  
 { {
     cleanup_handler *cu = new cleanup_handler(routine, parm);      StartWrapperArg *arg = new StartWrapperArg;
     try      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 == -1)
           rc = errno;
       if ((rc == EAGAIN) || (rc == ENOMEM))
     {     {
         _cleanup.insert_first(cu);          Threads::clear(_handle.thid);
           delete arg;
           return PEGASUS_THREAD_INSUFFICIENT_RESOURCES;
     }     }
     catch(IPCException& e)      else if (rc != 0)
     {     {
         delete cu;          Threads::clear(_handle.thid);
         throw;          delete arg;
           return PEGASUS_THREAD_SETUP_FAILURE;
     }     }
     return;      return PEGASUS_THREAD_OK;
   }
   
   Thread::Thread(
       ThreadReturnType(PEGASUS_THREAD_CDECL* start) (void*),
       void* parameter,
       Boolean detached)
       : _is_detached(detached),
         _start(start),
         _cleanup(),
         _tsd(),
         _thread_parm(parameter),
         _exit_code(0)
   {
       Threads::clear(_handle.thid);
 } }
  
 void Thread::cleanup_pop(Boolean execute) throw(IPCException)  Thread::~Thread()
 { {
     cleanup_handler *cu ;  
     try     try
     {     {
         cu = _cleanup.remove_first() ;          join();
           empty_tsd();
     }     }
     catch(IPCException& e)      catch (...)
     {     {
         PEGASUS_ASSERT(0);          // Do not allow the destructor to throw an exception
     }     }
     if(execute == true)  
         cu->execute();  
     delete cu;  
 } }
  
 #endif  #endif /* PEGASUS_HAVE_PTHREADS */
   
  
 //thread_data *Thread::put_tsd(Sint8 *key, void (*delete_func)(void *), Uint32 size, void *value) throw(IPCException)  //==============================================================================
   //
   // Windows Threads Implementation:
   //
   //==============================================================================
  
   #if defined(PEGASUS_HAVE_WINDOWS_THREADS)
  
 #ifndef PEGASUS_THREAD_EXIT_NATIVE  ThreadStatus Thread::run()
 void Thread::exit_self(PEGASUS_THREAD_RETURN exit_code)  
 { {
     // execute the cleanup stack and then return      // Note: A Win32 thread ID is not the same thing as a pthread ID.
    while( _cleanup.count() )      // Win32 threads have both a thread ID and a handle.  The handle
       // is used in the wait functions, etc.
       // 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;
   
       if (Threads::null(_handle.thid))
    {    {
        try          if (errno == EAGAIN)
        {        {
            cleanup_pop(true);              return PEGASUS_THREAD_INSUFFICIENT_RESOURCES;
        }        }
        catch(IPCException& e)          else
        {        {
           PEGASUS_ASSERT(0);              return PEGASUS_THREAD_SETUP_FAILURE;
           break;  
        }        }
    }    }
    _exit_code = exit_code;      return PEGASUS_THREAD_OK;
    exit_thread(exit_code);  
 } }
  
   void Thread::cancel()
   {
       _cancelled = true;
   }
  
 #endif  void Thread::thread_switch()
   {
       Sleep(0);
   }
  
   void Thread::sleep(Uint32 milliseconds)
   {
       Sleep(milliseconds);
   }
  
 ThreadPool::ThreadPool(Sint16 initial_size,  void Thread::join()
                        Sint16 max,  {
                        Sint16 min,      if (!Threads::null(_handle.thid))
                        Sint8 *key)      {
    : _max_threads(max), _min_threads(min),          if (!_is_detached)
      _current_threads(0), _waiters(initial_size),          {
      _pool_sem(0), _pool(true), _running(true),              if (!_cancelled)
      _dying(0)              {
 {                  // Emulate the unix join api. Caller sleeps until thread is
    _allocate_wait.tv_sec = 1;                  // done.
    _allocate_wait.tv_usec = 0;                  WaitForSingleObject(_handle.thid.handle, INFINITE);
    _deallocate_wait.tv_sec = 30;              }
    _deallocate_wait.tv_usec = 0;              else
    _deadlock_detect.tv_sec = 60;              {
    _deadlock_detect.tv_usec = 0;                  // Currently this is the only way to ensure this code does
    memset(_key, 0x00, 17);                  // not
    if(key != 0)                  // hang forever.
       strncpy(_key, key, 16);                  if (WaitForSingleObject(_handle.thid.handle, 10000) ==
    if(_max_threads < initial_size)                      WAIT_TIMEOUT)
       _max_threads = initial_size;                  {
    if(_min_threads > initial_size)                      TerminateThread(_handle.thid.handle, 0);
       _min_threads = initial_size;  
   
    int i;  
    for(i = 0; i < initial_size; i++)  
    {  
       _link_pool(_init_thread());  
    }    }
 } }
  
 ThreadPool::~ThreadPool(void)              DWORD exit_code = 0;
 {              GetExitCodeThread(_handle.thid.handle, &exit_code);
    _dying++;              _exit_code = (ThreadReturnType) exit_code;
    Thread *th = _pool.remove_first();  
    while(th != 0)  
    {  
       // signal the thread's sleep semaphore  
       th->cancel();  
       th->join();  
       th->empty_tsd();  
       delete th;  
       th = _pool.remove_first();  
    }  
 } }
  
 // make this static to the class          CloseHandle(_handle.thid.handle);
 PEGASUS_THREAD_RETURN PEGASUS_THREAD_CDECL ThreadPool::_loop(void *parm)          Threads::clear(_handle.thid);
 {      }
    Thread *myself = (Thread *)parm;  }
    if(myself == 0)  
       throw NullPointer();  
    ThreadPool *pool = (ThreadPool *)myself->get_parm();  
    if(pool == 0 )  
       throw NullPointer();  
    Semaphore *sleep_sem;  
    struct timeval *deadlock_timer;  
  
    try  void Thread::detach()
    {    {
       sleep_sem = (Semaphore *)myself->reference_tsd("sleep sem");      _is_detached = true;
       myself->dereference_tsd();  
       deadlock_timer = (struct timeval *)myself->reference_tsd("deadlock timer");  
       myself->dereference_tsd();  
    }    }
    catch(IPCException & e)  
   Thread::Thread(ThreadReturnType(PEGASUS_THREAD_CDECL * start) (void *),
                  void *parameter,
                  Boolean detached):_is_detached(detached),
   _cancelled(false),
   _start(start), _cleanup(), _tsd(), _thread_parm(parameter), _exit_code(0)
    {    {
       myself->exit_self(0);      Threads::clear(_handle.thid);
    }    }
    if(sleep_sem == 0 || deadlock_timer == 0)  
       throw NullPointer();  
  
    while(pool->_dying < 1)  Thread::~Thread()
    {    {
       myself->test_cancel();  
       sleep_sem->wait();  
       // when we awaken we reside on the running queue, not the pool queue  
       myself->test_cancel();  
       gettimeofday(deadlock_timer, NULL);  
   
       PEGASUS_THREAD_RETURN (PEGASUS_THREAD_CDECL *_work)(void *);  
       void *parm;  
   
       try       try
       {       {
          _work = (PEGASUS_THREAD_RETURN (PEGASUS_THREAD_CDECL *)(void *)) \          join();
             myself->reference_tsd("work func");          empty_tsd();
          myself->dereference_tsd();  
          parm = myself->reference_tsd("work parm");  
          myself->dereference_tsd();  
       }       }
       catch(IPCException & e)      catch (...)
       {       {
          myself->exit_self(0);      }
       }       }
  
       if(_work == 0)  #endif /* PEGASUS_HAVE_WINDOWS_THREADS */
          throw NullPointer();  
       _work(parm);  
  
       // put myself back onto the available list  //==============================================================================
       try  //
   // Common implementation:
   //
   //==============================================================================
   
   void thread_data::default_delete(void *data)
       {       {
          pool->_running.remove((void *)myself);      if (data != NULL)
          pool->_link_pool(myself);          ::operator  delete(data);
       }       }
       catch(IPCException & e)  
   void language_delete(void *data)
       {       {
          myself->exit_self(0);      if (data != NULL)
       }      {
           AutoPtr < AcceptLanguageList > al(static_cast <
                                             AcceptLanguageList * >(data));
    }    }
    myself->exit_self(0);  
    return((PEGASUS_THREAD_RETURN)0);  
 } }
  
   Boolean Thread::_signals_blocked = false;
   #ifndef PEGASUS_OS_ZOS
   TSDKeyType Thread::_platform_thread_key = TSDKeyType(-1);
   #else
   TSDKeyType Thread::_platform_thread_key;
   #endif
   Boolean Thread::_key_initialized = false;
   Boolean Thread::_key_error = false;
  
 void ThreadPool::allocate_and_awaken(void *parm,  void Thread::cleanup_push(void (*routine) (void *), void *parm)
                                      PEGASUS_THREAD_RETURN \  
                                      (PEGASUS_THREAD_CDECL *work)(void *))  
    throw(IPCException)  
 { {
    struct timeval start;      AutoPtr < cleanup_handler > cu(new cleanup_handler(routine, parm));
    gettimeofday(&start, NULL);      _cleanup.insert_front(cu.get());
       cu.release();
    Thread *th = _pool.remove_first();      return;
   }
  
    while (th == 0 && _dying < 1)  void Thread::cleanup_pop(Boolean execute)
    {    {
       try  // we couldn't get a free thread from the pool      AutoPtr < cleanup_handler > cu;
       try
       {       {
          // wait for the right interval and try again          cu.reset(_cleanup.remove_front());
          while(th == 0 && _dying < 1)      }
       catch (...)
          {          {
             _check_deadlock(&start);          PEGASUS_ASSERT(0);
             Uint32 interval = _allocate_wait.tv_sec * 1000;  
             if(_allocate_wait.tv_usec > 0)  
                interval += (_deallocate_wait.tv_usec / 1000);  
             // will throw a timeout if no thread comes free  
             _pool_sem.time_wait(interval);  
             th = _pool.remove_first();  
          }          }
       if (execute == true)
           cu->execute();
       }       }
       catch(TimeOut & to)  
   
   void Thread::exit_self(ThreadReturnType exit_code)
       {       {
          if(_current_threads < _max_threads)  #if !defined(PEGASUS_PLATFORM_AIX_RS_IBMCXX) \
       && !defined(PEGASUS_PLATFORM_PASE_ISERIES_IBMCXX)
       Threads::exit(exit_code);
   #else
       // execute the cleanup stack and then return
       while (_cleanup.size())
          {          {
             th = _init_thread();          try
             break;          {
               cleanup_pop(true);
          }          }
           catch (...)
           {
               PEGASUS_ASSERT(0);
               break;
       }       }
       // will throw a Deadlock Exception before falling out of the loop  
       _check_deadlock(&start);  
    } // while th == null  
   
    if(_dying < 1)  
    {  
       // initialize the thread data with the work function and parameters  
       th->remove_tsd("work func");  
       th->put_tsd("work func", NULL,  
                   sizeof( PEGASUS_THREAD_RETURN (PEGASUS_THREAD_CDECL *)(void *)),  
                   (void *)work);  
       th->remove_tsd("work parm");  
       th->put_tsd("work parm", NULL, sizeof(void *), parm);  
   
       // put the thread on the running list  
       _running.insert_first(th);  
   
       // signal the thread's sleep semaphore to awaken it  
       Semaphore *sleep_sem = (Semaphore *)th->reference_tsd("sleep sem");  
       if(sleep_sem == 0)  
          throw NullPointer();  
       sleep_sem->signal();  
    }    }
    else      _exit_code = exit_code;
       _pool.insert_first(th);      Threads::exit(exit_code);
       Threads::clear(_handle.thid);
   #endif
 } }
  
 // caller is responsible for only calling this routine during slack periods  Sint8 Thread::initializeKey()
 // but should call it at least once per _deadlock_detect with the running q  {
 // and at least once per _deallocate_wait for the pool q      PEG_METHOD_ENTER(TRC_THREAD, "Thread::initializeKey");
       if (!Thread::_key_initialized)
       {
           if (Thread::_key_error)
           {
               PEG_TRACE_CSTRING(TRC_THREAD, Tracer::LEVEL1,
                             "Thread: ERROR - thread key error");
               return -1;
           }
  
 void ThreadPool::_kill_dead_threads(DQueue<Thread> *q, Boolean (*check)(struct timeval *))          if (TSDKey::create(&Thread::_platform_thread_key) == 0)
    throw(IPCException)  
 { {
    struct timeval now;              PEG_TRACE_CSTRING(TRC_THREAD, Tracer::LEVEL4,
    gettimeofday(&now, NULL);                            "Thread: able to create a thread key");
               Thread::_key_initialized = true;
           }
           else
           {
               PEG_TRACE_CSTRING(TRC_THREAD, Tracer::LEVEL1,
                             "Thread: ERROR - unable to create a thread key");
               Thread::_key_error = true;
               return -1;
           }
       }
  
    DQueue<Thread> dead(true) ;      PEG_METHOD_EXIT();
       return 0;
   }
  
    if(q->count() > 0 )  Thread *Thread::getCurrent()
    {    {
       try      PEG_METHOD_ENTER(TRC_THREAD, "Thread::getCurrent");
       if (Thread::initializeKey() != 0)
       {       {
          q->try_lock();          return NULL;
       }       }
       catch(AlreadyLocked & a)      PEG_METHOD_EXIT();
       {      return (Thread *) TSDKey::get_thread_specific(_platform_thread_key);
          return;  
       }       }
  
       Thread *context = 0;  void Thread::setCurrent(Thread * thrd)
       struct timeval dt = { 0, 0 };  
       struct timeval *dtp;  
       Thread *th = q->next(context);  
       while (th != 0 )  
       {       {
          try      PEG_METHOD_ENTER(TRC_THREAD, "Thread::setCurrent");
       if (Thread::initializeKey() == 0)
       {
           if (TSDKey::
               set_thread_specific(Thread::_platform_thread_key,
                                   (void *) thrd) == 0)
          {          {
             dtp = (struct timeval *)th->try_reference_tsd("deadlock timer");              PEG_TRACE_CSTRING(TRC_THREAD, Tracer::LEVEL4,
                   "Successful set Thread * into thread specific storage");
          }          }
          catch(AlreadyLocked & a)          else
          {          {
             context = th;              PEG_TRACE_CSTRING(TRC_THREAD, Tracer::LEVEL1,
             th = q->next(context);                  "ERROR: error setting Thread * into thread specific storage");
             continue;          }
       }
       PEG_METHOD_EXIT();
          }          }
  
          if(dtp != 0)  AcceptLanguageList *Thread::getLanguages()
          {          {
             memcpy(&dt, dtp, sizeof(struct timeval));      PEG_METHOD_ENTER(TRC_THREAD, "Thread::getLanguages");
  
       Thread *curThrd = Thread::getCurrent();
       if (curThrd == NULL)
           return NULL;
       AcceptLanguageList *acceptLangs =
           (AcceptLanguageList *) curThrd->reference_tsd("acceptLanguages");
       curThrd->dereference_tsd();
       PEG_METHOD_EXIT();
       return acceptLangs;
          }          }
          th->dereference_tsd();  
          if( true == check(&dt))  void Thread::setLanguages(const AcceptLanguageList& langs)
          {          {
             th = q->remove_no_lock((void *)th);      PEG_METHOD_ENTER(TRC_THREAD, "Thread::setLanguages");
  
             if(th != 0)      Thread *currentThrd = Thread::getCurrent();
       if (currentThrd != NULL)
             {             {
                dead.insert_first(th);          AutoPtr<AcceptLanguageList> langsCopy(new AcceptLanguageList(langs));
                th = 0;  
             }          // deletes the old tsd and creates a new one
          }          currentThrd->put_tsd(
          context = th;              "acceptLanguages",
          th = q->next(context);              language_delete,
               sizeof (AcceptLanguageList *),
               langsCopy.get());
   
           langsCopy.release();
       }       }
       q->unlock();  
       PEG_METHOD_EXIT();
    }    }
  
    if(dead.count())  void Thread::clearLanguages()
    {    {
       Thread *th = dead.remove_first();      PEG_METHOD_ENTER(TRC_THREAD, "Thread::clearLanguages");
       while(th != 0)  
       Thread *currentThrd = Thread::getCurrent();
       if (currentThrd != NULL)
       {       {
          th->cancel();          // deletes the old tsd
          th->join();          currentThrd->delete_tsd("acceptLanguages");
          delete th;  
          th = dead.remove_first();  
       }  
    }  
    return;  
 } }
  
 Boolean ThreadPool::_check_time(struct timeval *start, struct timeval *interval)      PEG_METHOD_EXIT();
 {  
    struct timeval now;  
    gettimeofday(&now, NULL);  
    if( (now.tv_sec - start->tv_sec) > interval->tv_sec ||  
        (((now.tv_sec - start->tv_sec) == interval->tv_sec) &&  
         ((now.tv_usec - start->tv_usec) >= interval->tv_usec ) ) )  
       return true;  
    else  
       return false;  
 } }
  
   // ATTN: not sure where to put this!
   #ifdef PEGASUS_ZOS_SECURITY
   bool isEnhancedSecurity = 99;
   #endif
  
 PEGASUS_NAMESPACE_END PEGASUS_NAMESPACE_END
   


Legend:
Removed from v.1.1.2.13  
changed lines
  Added in v.1.107

No CVS admin address has been configured
Powered by
ViewCVS 0.9.2