Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does a function accept a void pointer?

I am trying to understand pthread.

However It is required to create thread methods as follows:

void *SomeMethod(void* x)
{
    //Do Something
}

Why is it necessary to create a function that accepts a void pointer? Can't we use pthread with a function like this?

void SomeMethod()
{
}
like image 532
ozgur Avatar asked Mar 25 '26 23:03

ozgur


2 Answers

Because the pthread_create function takes an argument of type void* (*)(void*) which is a function taking a void* and returning a void*, so to create a thread using pthread_create that's what you need to use.

The pthread_create API takes that to allow you to pass data to the new thread and get data back again. If you don't want to pass anything in you still have to meet that interface, but just pass it NULL.

Just because you don't want to pass any arguments to your new thread right now doesn't mean the API should be designed to only support your current use case. It's much better to have an API written in terms of a function taking void* (which can optionally be passed NULL) than to have an API in terms of a function taking no arguments and requiring users to come up with their own solutions for passing data to the new thread.

In C++ you can use any type of function for the new thread and pass it whatever arguments you need to:

std::thread t(&SomeMethod);
like image 119
Jonathan Wakely Avatar answered Mar 28 '26 14:03

Jonathan Wakely


Because quite often, we want to give the thread something to work on (or with, or off, or whatever). A very typical example is to pass in an instance of a class, so you can make calls to the class member functions.

But it could be all sorts of other things - a struct, or a pointer to some simple data.

Of course, using std::thread will hide most such things anyway, and you don't need to worry about it. I would strongly suggest using std::thread instead of pthread in general.

like image 30
Mats Petersson Avatar answered Mar 28 '26 14:03

Mats Petersson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!