Скачиваний:
17
Добавлен:
01.05.2014
Размер:
2.89 Кб
Скачать
#ifndef PKG_H
#define PKG_H
#include <fstream.h>
#include <stdio.h>
#include <thread.h>

/* record to store a set of thread-specific data */
class thr_data {
       int      errno;       // errno for a thread
       ofstream& ofs;        // output stream for a thread
       /* other stuffs */
   public:
       /* constructor */
       thr_data( int errval, ofstream& os)
           : errno(errval), ofs(os)
                     {};
       /* destructor */
       ~thr_data()   { ofs.close();  };

       /* return a thread's errno */
       int& errval() { return errno; };

       /* return a thread's ostream handle */
       ofstream& os(){ return ofs;   }; 

       /* other member functions */
};
   
/* Utility package class */
class Xpackage {
      thread_key_t   key;    // key for all threads
      ofstream       ocerr;  // default output stream
      /* other package data */
   public:
      /* called when a thread die. discard the
         the thread-specific data stored in key
      */
      friend void destr( void* valueP )
      {
           thr_data  *pDat = (thr_data*)valueP;
	   delete pDat;
      };

      /* coonstructor */
      Xpackage() : ocerr("err.log")
      {
         if (thr_keycreate(&key,destr)) 
             perror("thr_create");
      };

      /* destructor */
      ~Xpackage()  { ocerr.close(); };

      /* called when each thread starts */
      void new_thread( int errval,  ofstream& os )
      {
           thr_data       *pDat;
           /* alloc memory for a thread-specific data */
           pDat = new thr_data(errval, os);
           if (thr_setspecific(key,pDat))
               perror( "thr_setspecific");
      }; 

      /* set a thread's errno and return a value */
      int set_errno( int rc ) 
      {
           thr_data       *pDat;
           if (thr_getspecific(key,(void**)&pDat))
              perror("thr_getspecific");
           else pDat->errval() = rc;
           return rc==0 ? 0 : -1;
      };

      /* return current errno value for a thread */
      int errno() 
      {
           thr_data       *pDat;
           if (!thr_getspecific(key,(void**)&pDat))
           {
              return pDat->errval();
           }
           perror("thr_getspecific");
           return -1;
      };

      /* return a thread's outstream handle */
      ofstream& os() 
      {
           thr_data       *pDat;
           if (!thr_getspecific(key,(void**)&pDat))
           {
              return pDat->os();
           }
           perror("thr_getspecific");
           return ocerr;
      };

      /* a sample package function */
      int chgErrno(int new_val ) 
      {
           new_val += (int)thr_self();
           return set_errno( new_val );
      };

      /* other package functions */
};
    
#endif
Соседние файлы в папке pkg