Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do we pass function arguments as void* in pthread_create?

I have just started an Operating System course and currently we are learning multi-threading, so I am new to all this.

Here is my question: Whenever we create a thread using pthread_create(), why do we need to pass the arguments of the function we want our thread to run in type void*?

For example, consider the following code.

void *test(void* data)
{
   ...
}

int main()
{
      int temp;
      pthread_t tid;
      pthread_attr_t attr;
   
      pthread_attr_init(&attr);
      pthread_create(&tid, &attr, test, (void*)&temp);
}

So, here in,

pthread_create(&tid, &attr, test, (void*)&temp);

why do we need to type cast the integer to void*. Why not just pass integer as is? And similarly, instead of

void* test(void* data);

why not this,

void* test(int data);
like image 607
Muzahir Hussain Avatar asked Apr 28 '26 05:04

Muzahir Hussain


1 Answers

First off, pthread_create() is a C function, not C++, so all the things C++ could do at this point -- e.g. something using templates -- is not possible. C programs want to start threads as well.

(Actually newer versions of C++ have their own threading interface.)

So, C.

The idea is to have a generic interface, so you can pass anything to any function to be called by pthread_create(), and return anything as well.

You can't pass-by-value, because you don't know the size of the argument. Is it int, double, or struct something? So you need to pass by pointer.

And since you don't know the type of the argument (and return value) either, you use void *, the "anonymous" pointer type. Inside the called thread function (test() in this case), you do know the type of the argument and return value, so you can cast from and to void * as appropriate.

like image 90
DevSolar Avatar answered Apr 30 '26 19:04

DevSolar