Rishabh Malhotra
Rishabh Malhotra

Reputation: 25

Thread Declaration in C++

I was going through a project code in C. In there, I saw this declaration of thread :

pthread_t ui_thread = (pthread_t) 0;

I didn't understand the part starting from '=' operator. What is it and how can I code the same declaration in C++.

Upvotes: 0

Views: 79

Answers (2)

quamrana
quamrana

Reputation: 39404

The (pthread_t) part is known as type casting in C. Also called explicit type conversion. It is just a way for the programmer to inform the compiler that the programmer means for the value (0 in this case) to be treated as the type pthread_t.

The code you have is still valid C++.

In C++11 you can probably just do this:

pthread_t ui_thread{nullptr};

Upvotes: 0

Anthony Williams
Anthony Williams

Reputation: 68631

(pthread_t) 0 converts the literal integer value 0 to a thread handle pthread_t. This assumes that such a conversion is possible, and valid, and that this is a meaningful value (probably expected to be "no thread").

The full statement creates a variable ui_thread which is a thread handle of type pthread_t, and initializes it with this value.

In C++, you could probably write the same if you were on a platform where it was valid for C. However, you would be better to use the C++ thread library.

std::thread t;

will create a default-constructed thread handle with no associated thread, which is likely the equivalent to the above.

Upvotes: 1

Related Questions