PTLib
Version 2.18.8
|
This class defines a thread of execution in the system. More...
#include <thread.h>
Classes | |
class | LocalStorageBase |
Thread local storage base class, see PThreadLocalStorage for template. More... | |
struct | Times |
Times for execution of the thread. More... | |
Public Member Functions | |
bool | IsAutoDelete () const |
int | PXBlockOnChildTerminate (int pid, const PTimeInterval &timeout) |
int | PXBlockOnIO (int handle, int type, const PTimeInterval &timeout) |
void | PXAbortBlock () const |
Overrides from <code>PObject</code> | |
void | PrintOn (ostream &strm) const |
Standard stream print function. More... | |
![]() | |
__inline unsigned | GetTraceContextIdentifier () const |
Get PTRACE context identifier. More... | |
__inline void | SetTraceContextIdentifier (unsigned id) |
__inline void | SetTraceContextIdentifier (const PObject &obj) |
__inline void | SetTraceContextIdentifier (const PObject *obj) |
__inline void | CopyTraceContextIdentifier (PObject &obj) const |
__inline void | CopyTraceContextIdentifier (PObject *obj) const |
virtual | ~PObject () |
__inline const char * | GetClass () const |
__inline bool | IsClass (const char *name) const |
__inline const PObject * | PTraceObjectInstance () const |
virtual PObject * | Clone () const |
Create a copy of the class on the heap. More... | |
template<class CLS > | |
CLS * | CloneAs () const |
As for Clone() but converts to specified type. More... | |
virtual PINDEX | HashFunction () const |
This function yields a hash value required by the PDictionary class. More... | |
virtual Comparison | Compare (const PObject &obj) const |
Compare the two objects and return their relative rank. More... | |
virtual Comparison | CompareObjectMemoryDirect (const PObject &obj) const |
Determine the byte wise comparison of two objects. More... | |
bool | operator== (const PObject &obj) const |
Compare the two objects. More... | |
bool | operator!= (const PObject &obj) const |
Compare the two objects. More... | |
bool | operator< (const PObject &obj) const |
Compare the two objects. More... | |
bool | operator> (const PObject &obj) const |
Compare the two objects. More... | |
bool | operator<= (const PObject &obj) const |
Compare the two objects. More... | |
bool | operator>= (const PObject &obj) const |
Compare the two objects. More... | |
virtual void | ReadFrom (istream &strm) |
Input the contents of the object from the stream. More... | |
Protected Types | |
enum | Type { e_IsAutoDelete, e_IsManualDelete, e_IsProcess, e_IsExternal } |
Protected Attributes | |
enum PThread::Type | m_type |
PINDEX | m_originalStackSize |
PString | m_threadName |
PCriticalSection | m_threadNameMutex |
PThreadIdentifier | m_threadId |
PUniqueThreadIdentifier | m_uniqueId |
![]() | |
unsigned | m_traceContextIdentifier |
Construction | |
enum | AutoDeleteFlag { AutoDeleteThread, NoAutoDeleteThread } |
Codes for thread autodelete flag. More... | |
P_DECLARE_TRACED_ENUM (Priority, LowestPriority, LowPriority, NormalPriority, HighPriority, HighestPriority) | |
Codes for thread priorities. More... | |
PThread (PINDEX stack, AutoDeleteFlag deletion=AutoDeleteThread, Priority priorityLevel=NormalPriority, const PString &threadName=PString::Empty()) | |
Create a new thread instance. More... | |
~PThread () | |
Destroy the thread, this simply calls the Terminate() function with all its restrictions and penalties. More... | |
Control functions | |
virtual void | Restart () |
Restart a terminated thread using the same stack priority etc that was current when the thread terminated. More... | |
virtual void | Terminate () |
Terminate the thread. More... | |
virtual PBoolean | IsTerminated () const |
Determine if the thread has been terminated or ran to completion. More... | |
void | WaitForTermination () const |
Block and wait for the thread to terminate. More... | |
PBoolean | WaitForTermination (const PTimeInterval &maxWait) const |
Block and wait for the thread to terminate. More... | |
virtual void | Suspend (PBoolean susp=true) |
Suspend or resume the thread. More... | |
virtual void | Resume () |
Resume thread execution, this is identical to Suspend(false) . More... | |
virtual PBoolean | IsSuspended () const |
Determine if the thread is currently suspended. More... | |
virtual void | SetPriority (Priority priorityLevel) |
Set the priority of the thread relative to other threads in the current process. More... | |
virtual Priority | GetPriority () const |
Get the current priority of the thread in the current process. More... | |
virtual void | SetAutoDelete (AutoDeleteFlag deletion=AutoDeleteThread) |
Set the flag indicating thread object is to be automatically deleted when the thread ends. More... | |
void | SetNoAutoDelete () |
Reet the flag indicating thread object is to be automatically deleted when the thread ends. More... | |
virtual PString | GetThreadName () const |
Get the name of the thread. More... | |
virtual void | SetThreadName (const PString &name) |
Change the name of the thread. More... | |
static bool | WaitAndDelete (PThread *&thread, const PTimeInterval &maxWait=10000, PMutex *mutex=NULL, bool lock=true) |
Wait for thread termination and delete object. More... | |
static void | Sleep (const PTimeInterval &delay) |
Suspend the current thread for the specified amount of time. More... | |
static PString | GetThreadName (PThreadIdentifier id) |
Get the name of the thread. More... | |
static PString | GetCurrentThreadName () |
Get the current threads name. More... | |
static PString | GetIdentifiersAsString (PThreadIdentifier tid, PUniqueThreadIdentifier uid) |
Convert to thread identifers as a string. More... | |
Miscellaneous | |
PPROFILE_EXCLUDE (PThreadIdentifier GetThreadId() const ) | |
PPROFILE_EXCLUDE (static PThreadIdentifier GetCurrentThreadId()) | |
PPROFILE_EXCLUDE (PUniqueThreadIdentifier GetUniqueIdentifier() const ) | |
PPROFILE_EXCLUDE (static PUniqueThreadIdentifier GetCurrentUniqueIdentifier()) | |
PPROFILE_EXCLUDE (static PINDEX GetTotalCount()) | |
PPROFILE_EXCLUDE (bool GetTimes(Times ×)) | |
PPROFILE_EXCLUDE (static bool GetTimes(PThreadIdentifier id, Times ×)) | |
PPROFILE_EXCLUDE (static void GetTimes(std::vector< Times > ×)) | |
virtual void | Main ()=0 |
User override function for the main execution routine of the thread. More... | |
static void | GetTimes (std::list< Times > ×) |
static void | GetTimes (std::set< Times > ×) |
static int | GetPercentageCPU (Times &previousTimes, const PTimeInterval &period=PTimeInterval(0, 1), PThreadIdentifier id=PNullThreadIdentifier) |
Calculate the percentage CPU used over a period of time. More... | |
static unsigned | GetNumProcessors () |
Get number of processors, or processor cores, this machine has available. More... | |
static PThread * | Current () |
Get the currently running thread object instance. More... | |
static void | Yield () |
Yield to another thread without blocking. More... | |
static PThread * | Create (const PNotifier ¬ifier, INT parameter=0, AutoDeleteFlag deletion=AutoDeleteThread, Priority priorityLevel=NormalPriority, const PString &threadName=PString::Empty(), PINDEX stackSize=0) |
Create a simple thread executing the specified notifier. More... | |
static PThread * | Create (const PNotifier ¬ifier, const PString &threadName) |
Additional Inherited Members | |
![]() | |
enum | Comparison { LessThan = -1, EqualTo = 0, GreaterThan = 1 } |
Result of the comparison operation performed by the Compare() function. More... | |
![]() | |
static __inline void | CopyTraceContextIdentifier (PObject &to, const PObject &from) |
static __inline void | CopyTraceContextIdentifier (PObject &to, const PObject *from) |
static __inline void | CopyTraceContextIdentifier (PObject *to, const PObject &from) |
static __inline void | CopyTraceContextIdentifier (PObject *to, const PObject *from) |
static __inline const char * | Class () |
static __inline const PObject * | PTraceObjectInstance (const char *) |
static __inline const PObject * | PTraceObjectInstance (const PObject *obj) |
template<typename T > | |
static Comparison | Compare2 (T v1, T v2) |
Compare two types, returning Comparison type. More... | |
static Comparison | InternalCompareObjectMemoryDirect (const PObject *obj1, const PObject *obj2, PINDEX size) |
Internal function caled from CompareObjectMemoryDirect() More... | |
![]() | |
PObject () | |
Constructor for PObject, made protected so cannot ever create one on its own. More... | |
This class defines a thread of execution in the system.
A thread is an independent flow of processor instructions. This differs from a process which also embodies a program address space and resource allocation. So threads can share memory and resources as they run in the context of a given process. A process always contains at least one thread. This is reflected in this library by the PProcess
class being descended from the PThread
class.
The implementation of a thread is platform dependent, but it is assumed that the platform has some support for native threads. Previous versions of PTLib/PWLib have some support for co-operative threads, but this has been removed.
|
protected |
PThread::PThread | ( | PINDEX | stack, |
AutoDeleteFlag | deletion = AutoDeleteThread , |
||
Priority | priorityLevel = NormalPriority , |
||
const PString & | threadName = PString::Empty() |
||
) |
Create a new thread instance.
Unless the startSuspended
parameter is true
, the threads Main()
function is called to execute the code for the thread.
Note that the exact timing of the execution of code in threads can never be predicted. Thus you you can get a race condition on intialising a descendent class. To avoid this problem a thread is always started suspended. You must call the Resume()
function after your descendent class construction is complete.
If synchronisation is required between threads then the use of semaphores is essential.
If the deletion
is set to AutoDeleteThread
then the PThread
is assumed to be allocated with the new operator and may be freed using the delete operator as soon as the thread is terminated or executes to completion (usually the latter).
The stack size argument is highly platform specific and should alamost always be zero for the default.
stack | Stack size on some platforms, 0 == default |
deletion | Automatically delete PThread instance on termination of thread. |
priorityLevel | Initial priority of thread. |
threadName | The name of the thread (for Debug/Trace) |
PThread::~PThread | ( | ) |
Destroy the thread, this simply calls the Terminate()
function with all its restrictions and penalties.
See that function for more information.
Note that the correct way for a thread to terminate is to return from the Main()
function.
|
static |
Create a simple thread executing the specified notifier.
This creates a simple PThread
class that automatically executes the function defined by the PNotifier
in the context of a new thread.
notifier | Function to execute in thread. |
parameter | Parameter value to pass to notifier. |
deletion | Automatically delete PThread instance on termination of thread. |
priorityLevel | Initial priority of thread. |
threadName | The name of the thread (for Debug/Trace) |
stackSize | Stack size on some platforms, 0 == default |
Referenced by Create().
|
inlinestatic |
notifier | Function to execute in thread. |
threadName | The name of the thread (for Debug/Trace) |
References Create(), and NoAutoDeleteThread.
|
static |
Get the currently running thread object instance.
It is possible, even likely, that the smae code may be executed in the context of differenct threads. Under some circumstances it may be necessary to know what the current codes thread is and this static function provides that information.
|
inlinestatic |
Get the current threads name.
References GetThreadName().
|
static |
Convert to thread identifers as a string.
For platforms where unique thread id is different from the "normal" thread id, then the output will append it to the thread id string, e.g. "0x12345678 (54321)".
|
static |
Get number of processors, or processor cores, this machine has available.
|
static |
Calculate the percentage CPU used over a period of time.
Usage: PThread::Times previous; for (;;) { DoStuff(); unsigned percentage; if (PThread::GetPercentageCPU(previous, percentage, 2000) && percentage > 90) cout << "Excessive CPU used!" << end; }
period
. previousTimes | Previous CPU times, contecxt for calculations |
period | Time over which to integrate the average CPU usage. |
id | Thread ID to get CPU usage, null means current thread |
|
virtual |
Get the current priority of the thread in the current process.
|
virtual |
Get the name of the thread.
Thread names are a optional debugging aid.
Referenced by GetCurrentThreadName().
|
static |
Get the name of the thread.
Thread names are a optional debugging aid.
|
static |
times | Times for thread execution. |
|
static |
times | Times for thread execution. |
|
inline |
References e_IsAutoDelete, and m_type.
|
virtual |
Determine if the thread is currently suspended.
This checks the suspension count and if greater than zero returns true
for a suspended thread.
true
if thread is suspended.
|
virtual |
Determine if the thread has been terminated or ran to completion.
true
if the thread has been terminated.
|
pure virtual |
User override function for the main execution routine of the thread.
A descendent class must provide the code that will be executed in the thread within this function.
Note that the correct way for a thread to terminate is to return from this function.
Implemented in PThreadObj2Arg< ObjType, Arg1Type, Arg2Type >, PThreadObj1Arg< ObjType, Arg1Type >, PThreadObj< ObjType >, PThreadObj< PSNMPServer >, PLibraryProcess, PThread3Arg< Arg1Type, Arg2Type, Arg3Type >, PThread2Arg< Arg1Type, Arg2Type >, PThread1Arg< Arg1Type >, PThreadFunctor< Functor >, PThreadMain, XMPP::BaseStreamHandler, PThreadPoolBase::WorkerThreadBase, and PServiceProcess.
PThread::P_DECLARE_TRACED_ENUM | ( | Priority | , |
LowestPriority | , | ||
LowPriority | , | ||
NormalPriority | , | ||
HighPriority | , | ||
HighestPriority | |||
) |
Codes for thread priorities.
PThread::PPROFILE_EXCLUDE | ( | PThreadIdentifier GetThreadId() | const | ) |
const | Get operating system specific thread identifier for this thread. |
PThread::PPROFILE_EXCLUDE | ( | static PThreadIdentifier | GetCurrentThreadId() | ) |
GetCurrentThreadId | Get operating system specific thread identifier for the current thread. |
PThread::PPROFILE_EXCLUDE | ( | PUniqueThreadIdentifier GetUniqueIdentifier() | const | ) |
const | This returns a unique number for the thread. For most platforms this is identical to GetThreadId(), but others, e.g. Linux, it is different and GetThreadId() return values get re-used during the run of the process. |
PThread::PPROFILE_EXCLUDE | ( | static PUniqueThreadIdentifier | GetCurrentUniqueIdentifier() | ) |
GetCurrentUniqueIdentifier | This returns a unique number for the currentthread. |
PThread::PPROFILE_EXCLUDE | ( | static PINDEX | GetTotalCount() | ) |
GetTotalCount | Get the total number of threads. |
PThread::PPROFILE_EXCLUDE | ( | bool | GetTimesTimes × | ) |
GetTimes | Get the thread execution times. |
PThread::PPROFILE_EXCLUDE | ( | static bool | GetTimesPThreadIdentifier id, Times × | ) |
GetTimes | Get the thread execution times. |
PThread::PPROFILE_EXCLUDE | ( | static void | GetTimesstd::vector< Times > × | ) |
GetTimes | Get the thread execution times for all threads. |
|
virtual |
void PThread::PXAbortBlock | ( | ) | const |
int PThread::PXBlockOnChildTerminate | ( | int | pid, |
const PTimeInterval & | timeout | ||
) |
int PThread::PXBlockOnIO | ( | int | handle, |
int | type, | ||
const PTimeInterval & | timeout | ||
) |
|
virtual |
Restart a terminated thread using the same stack priority etc that was current when the thread terminated.
If the thread is still running then this function is ignored.
|
virtual |
Resume thread execution, this is identical to Suspend(false)
.
The Resume() method may be called from within the constructor of a PThread descendant. However, the Resume()
should be in the constructor of the most descendant class. So, if you have a class B (which is descended of PThread), and a class C (which is descended of B), placing the call to Resume()
in the constructor of B is unwise.
If you do place a call to Resume()
in the constructor, it should be at the end of the constructor, after all the other initialisation in the constructor.
The reason the call to Resume()
should be at the end of the construction process is simple - you want the thread to start when all the variables in the class have been correctly initialised.
Referenced by PThread1Arg< Arg1Type >::PThread1Arg(), PThread2Arg< Arg1Type, Arg2Type >::PThread2Arg(), PThread3Arg< Arg1Type, Arg2Type, Arg3Type >::PThread3Arg(), PThreadFunctor< Functor >::PThreadFunctor(), PThreadMain::PThreadMain(), PThreadObj< PSNMPServer >::PThreadObj(), PThreadObj1Arg< ObjType, Arg1Type >::PThreadObj1Arg(), and PThreadObj2Arg< ObjType, Arg1Type, Arg2Type >::PThreadObj2Arg().
|
virtual |
Set the flag indicating thread object is to be automatically deleted when the thread ends.
deletion | New auto delete setting. |
Referenced by SetNoAutoDelete().
|
inline |
Reet the flag indicating thread object is to be automatically deleted when the thread ends.
References NoAutoDeleteThread, and SetAutoDelete().
|
virtual |
Set the priority of the thread relative to other threads in the current process.
priorityLevel | New priority for thread. |
|
virtual |
Change the name of the thread.
Thread names are a optional debugging aid.
name | New name for the thread. |
|
static |
Suspend the current thread for the specified amount of time.
delay | Time interval to sleep for. |
|
virtual |
Suspend or resume the thread.
If susp
is true
this increments an internal count of suspensions that must be matched by an equal number of calls to Resume()
or Suspend(false)
before the thread actually executes again.
If susp
is false
then this decrements the internal count of suspensions. If the count is <= 0 then the thread will run. Note that the thread will not be suspended until an equal number of Suspend(true)
calls are made.
susp | Flag to suspend or resume a thread. |
|
virtual |
Terminate the thread.
It is highly recommended that this is not used except in abnormal abort situations as not all clean up of resources allocated to the thread will be executed. This is especially true in C++ as the destructors of objects that are automatic variables are not called causing at the very least the possiblity of memory leaks.
Note that the correct way for a thread to terminate is to return from the Main()
function or self terminate by calling Terminate()
within the context of the thread which can then assure that all resources are cleaned up.
Reimplemented in PProcess.
|
static |
Wait for thread termination and delete object.
The thread pointer is set to NULL within an optional mutex. The mutex is released before waiting for thread termination, which avoids deadlock scenarios. The lock
parameter indicates if the mutex is already locked on entry and should not be locked again, preventing the unlock from occurring due to nested mutex semantics.
If the maxTime
timeout occurs, the thread is preemptively destroyed which is very likely to cause many issues, see PThread::Terminate() so a PAssert is raised when this condition occurs.
true
if the thread forcibly terminated, false
if orderly exit. thread | Thread to delete |
maxWait | Maximum time to wait for termination. |
mutex | Optional mutex to protect setting of thread variable |
lock | Mutex should be locked. |
void PThread::WaitForTermination | ( | ) | const |
Block and wait for the thread to terminate.
Referenced by PThread1Arg< Arg1Type >::~PThread1Arg(), PThread2Arg< Arg1Type, Arg2Type >::~PThread2Arg(), PThread3Arg< Arg1Type, Arg2Type, Arg3Type >::~PThread3Arg(), PThreadFunctor< Functor >::~PThreadFunctor(), PThreadMain::~PThreadMain(), PThreadObj< PSNMPServer >::~PThreadObj(), PThreadObj1Arg< ObjType, Arg1Type >::~PThreadObj1Arg(), and PThreadObj2Arg< ObjType, Arg1Type, Arg2Type >::~PThreadObj2Arg().
PBoolean PThread::WaitForTermination | ( | const PTimeInterval & | maxWait | ) | const |
Block and wait for the thread to terminate.
false
if the thread has not terminated and the timeout has expired, true
otherwise. maxWait | Maximum time to wait for termination. |
|
static |
Yield to another thread without blocking.
This duplicates the implicit thread yield that may occur on some I/O operations or system calls.
This may not be implemented on all platforms.
|
protected |
|
protected |
|
protected |
|
protected |
|
protected |
Referenced by IsAutoDelete().
|
protected |