开发者

How to pass parameters to a thread in c multithreading properly

开发者 https://www.devze.com 2023-01-26 08:16 出处:网络
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 un

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_v开发者_如何转开发eg)

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.


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.


pthread_create is defined as follows:

int pthread_create(pthread_t *restrict thread, const pthread_attr_t *restrict attr,
     void *(*start_routine)(void *), void *restrict arg);

So it expects a void * as its last parameter. If you omit the cast, the compiler would give you a warning.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号