00001
00002
00003
00004 #ifndef __J2K__Basic_PThread_CPP__
00005 #define __J2K__Basic_PThread_CPP__
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018
00019 #include <j2k/445/Posix/Basic_PThread.hpp>
00020
00021
00022
00023
00024
00025
00026
00027
00028
00029
00030
00031
00032
00033
00034
00035
00036
00037
00038 inline Basic_PThread::Basic_PThread( BOOL autostart = FALSE, BOOL autojoin = FALSE )
00039 : pid( INVALID_PID ), isDetached( TRUE )
00040 {
00041
00042
00043
00044 #if (__sun) || (__SUN__)
00045
00046 thr_setconcurrency( sysconf(_SC_NPROCESSORS_ONLN) + 3 );
00047
00048 #endif
00049
00050 if ( autostart ) start();
00051 if ( autojoin ) join();
00052 }
00053
00054
00055 inline Basic_PThread::~Basic_PThread()
00056 {
00057 stop();
00058 end();
00059 }
00060
00061 void Basic_PThread::start( int start_prio )
00062 {
00063 if ( pid >= 0 && pid != INVALID_PID ) return;
00064
00065 memset( &attr, 0, sizeof( attr ) );
00066 memset( ¶m, 0, sizeof( param ) );
00067
00068 pthread_attr_init( &attr );
00069 pthread_attr_setscope( &attr, PTHREAD_SCOPE_SYSTEM );
00070 pthread_attr_setdetachstate( &attr, PTHREAD_CREATE_JOINABLE );
00071
00072 pthread_attr_setinheritsched( &attr, PTHREAD_EXPLICIT_SCHED );
00073 pthread_attr_setschedparam( &attr, ¶m );
00074
00075 param.sched_priority = start_prio;
00076 pthread_setschedparam( pthread_self(), SCHED_RR, ¶m );
00077 pthread_setschedparam( pid, SCHED_RR, ¶m );
00078
00079
00080 int rc = pthread_create( &pid, &attr, Wrapper, (void*)this );
00081
00082 if ( rc == -1 ) printf( "Forgot to include libraries: g++ -lpthread -lrt -lsocket -lnsl -g Basic_PThread.cpp" );
00083
00084 MC_OnError( rc, Error, "while starting a basic pthread." )
00085
00086 detach();
00087
00088
00089 }
00090
00091 inline void Basic_PThread::stop() {
00092 if ( pid < 0 ) return;
00093
00094 pthread_cancel( pid );
00095 pid = INVALID_PID;
00096 }
00097
00098 inline void Basic_PThread::end() {
00099 pthread_exit( NULL );
00100 }
00101
00102 inline pid_t Basic_PThread::getPID()
00103 {
00104 return pid;
00105 }
00106
00107 inline BOOL Basic_PThread::isStarted()
00108 {
00109 return ( pid >= 0 && pid != INVALID_PID );
00110 }
00111
00112 inline void Basic_PThread::yield()
00113 {
00114 sched_yield();
00115 }
00116
00117 inline void Basic_PThread::detach()
00118 {
00119 if ( pid < 0 ) return;
00120 if ( isDetached ) return;
00121
00122 int err = pthread_detach( pid );
00123 isDetached = TRUE;
00124
00125 MC_OnError( err, Error, "An error occured while detaching a PThread." );
00126 }
00127
00128
00129 inline void Basic_PThread::join( void** value_ptr = NULL )
00130 {
00131 int err = 0;
00132 if ( pid < 0 ) return;
00133 if ( !isDetached )
00134 err = pthread_join( pid, value_ptr );
00135
00136 isDetached = FALSE;
00137 MC_OnError( err, Error, "An error occured while joining a PThread." );
00138 }
00139
00140 #endif