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?
pthread_t is the data type used to uniquely identify a thread. It is returned by pthread_create() and used by the application in function calls that require a thread identifier.
pthread_create() returns zero when the call completes successfully. Any other return value indicates that an error occurred.
The pthread_create() function creates a thread with the specified attributes and runs the C function start_routine in the thread with the single pointer argument specified.
The pthread_join() function provides a simple mechanism allowing an application to wait for a thread to terminate. After the thread terminates, the application may then choose to clean up resources that were used by the thread.
pthread_t
is a C type, so it must have a trivial default constructor; so you can just value-initialize it:
: thread(), // ...
Your usage of threadValid
seems somewhat confused. It would be better to make it a bool
initially set to false
and then only set it true
once pthread_create
succeeds.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With