I was a bit confused with the following piece of code which just creates a number of threads and assigns them an id.
#include "pthread.h"
#include "stdio.h"
#include "stdlib.h"
#define N 5
void *worker_thread(void *arg) {
printf("This is worker_thread #%ld\n", (long) arg);
pthread_exit(NULL);
}
int main() {
pthread_t my_thread[N];
long id;
for (id = 1; id <= N; id++) {
int ret = pthread_create(&my_thread[id], NULL, &worker_thread, (void*) id);
if (ret != 0) {
printf("Error: pthread_create() failed\n");
exit(EXIT_FAILURE);
}
}
pthread_exit(NULL);
}
The function prototype was;
int ret = pthread_create(&my_thread[id], NULL, &worker_thread, (void*) &id);
You can of course but this will mean that the referred value should be there when the function exists, which isn't a problem here because we are in main(). The more prominent problem is that the value of id might change when the thread routine actually uses it, so it's not a good idea to pass the argument by reference.
But how can we do that?
In fact casting a long to a void* is allowed, it just means that the void* is actually not storing any pointer to a real memory location but a mere number represented by id. (void*) id returns some value and this is not a real memory address at all.
You can do the same with integers.
void *threadfunc(void *param)
{
int id = (intptr_t) param;
...
}
int i, r;
r = pthread_create(&thread, NULL, threadfunc, (void *) (intptr_t) i);
#include "pthread.h"
#include "stdio.h"
#include "stdlib.h"
#define N 5
void *worker_thread(void *arg) {
printf("This is worker_thread #%ld\n", (long) arg);
pthread_exit(NULL);
}
int main() {
pthread_t my_thread[N];
long id;
for (id = 1; id <= N; id++) {
int ret = pthread_create(&my_thread[id], NULL, &worker_thread, (void*) id);
if (ret != 0) {
printf("Error: pthread_create() failed\n");
exit(EXIT_FAILURE);
}
}
pthread_exit(NULL);
}
The function prototype was;
int pthread_create(pthread_t *thread, const pthread_attr_t *attr, void *(*start_routine) (void *), void *arg);
The arg was void*, Shouldn't we have;
int ret = pthread_create(&my_thread[id], NULL, &worker_thread, (void*) &id);
You can of course but this will mean that the referred value should be there when the function exists, which isn't a problem here because we are in main(). The more prominent problem is that the value of id might change when the thread routine actually uses it, so it's not a good idea to pass the argument by reference.
But how can we do that?
In fact casting a long to a void* is allowed, it just means that the void* is actually not storing any pointer to a real memory location but a mere number represented by id. (void*) id returns some value and this is not a real memory address at all.
You can do the same with integers.
#include
"stdint.h"
Comments
Post a Comment