Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass parameters to a thread in c multithreading properly

I'm trying to learn on C multithreading, and I've seen a couple of rare things.

I understand that passing parameters to a thread must be done with pointers. I've found an example which I don't understand. I'll copy the relevant lines:

pthread_t tid[MAX_THREADS]
int n_veg
pthread_create(&tid[n],NULL,caracter,(void *)n_veg)

caracter is obviously a predeclared function.

Now, why do we use a void pointer casting instead of a int pointer casting? Is there any relevant difference?

Secondly, why do we use a pointer casting in the first place? Can't we use "&n_veg" like with the first parameter?

Thanks in advance.

like image 248
bluehallu Avatar asked Dec 29 '22 05:12

bluehallu


1 Answers

Since both your questions are related, I'll answer them together: pthread_create takes a void * parameter, so you can really pass in any pointer you want. In this case though, we aren't actually passing a pointer, but just a simple integer value casted as a pointer. That means you will access it like this in caracter:

int value = (int)n_veg;

As you mentioned, you could very well pass an actual pointer as &n_veg and retrieve the value like this:

int value = *(int *)n_veg;

In fact, in most cases, you will need to pass more data than just an integer, such as a structure, and in that case, you must pass a pointer, as you can't simply cast it to a pointer like an integer.

One thing to keep in mind when you pass a pointer is that n_veg must not go out of scope as long as the thread is running. For example, if you do:

void test() {
  int n_veg;
  pthread_create(&tid[n],NULL,caracter,&n_veg);
}

then &n_veg will be invalid as soon as test returns, but the thread may still be running and will be holding an invalid address. Because of this, structures passed to threads are normally dynamically allocated, say using malloc, and the thread can free it once it has completed.

like image 158
casablanca Avatar answered Jan 17 '23 13:01

casablanca