I understand that pthread_t
should be treated as an opaque value, however I don't know how to initialize it when used as a class member, and how can I check for its validity.
Consider this code sample:
class MyClass
{
public:
pthread_t thread;
MyClass()
: thread(0) // Wrong because pthread_t should be an opaque value,
// so how should I initialize it?
{}
~MyClass()
{
if( thread ) // Wrong, but how can I verify if it is valid?
pthread_join(thread, NULL);
}
};
I also understand that if pthread_create()
fails, the pthread_t
value may be inconsistent. So I should only rely on the return value from pthread_create()
. But this means that I should keep this returned value along with pthread_t
and use it to check thread validity? And in this case, how should I initialize in the class constructor this value?
class MyClass
{
public:
pthread_t thread;
int threadValid;
MyClass()
: thread(0), // Wrong because pthread_t should be an opaque value,
// so how should I initialize it?
, threadValid(1) // pthread_create return zero in case of success,
// so I can initialize this to any nonzero value?
{}
~MyClass()
{
if( threadValid == 0 ) // Nonzero means thread invalid.
// Is this the correct approach?
{
pthread_join(thread, NULL);
threadValid = 1;
}
}
};
I have a Windows API background, and there a thread has its HANDLE
value, which may be initialized safely to NULL
, and can be checked against NULL
, and if CreateThread()
fails, it just consistently returns NULL
. There's no way, with pthreads, to keep this neat and simple approach?