Pass integer value through pthread_create
I simply want to pass the value of an integer to a thread.
How can I do that?
I tried:
int i;
pthread_t thread_tid[10];
for(i=0; i<10; i++)
{
pthread_create(&thread_tid[i], NULL, collector, i);
}
The thread method looks like this:
void *collector( void *arg)
{
int a = (int) arg;
...
I get the following warning:
warning: cast from pointer to integer of different size [-Wpointer-to-int-cast]
Solution 1:
The compiler will complain if you don't cast i
to a void pointer:
pthread_create(&thread_tid[i], NULL, collector, (void*)i);
That said, casting an integer to a pointer isn't strictly safe:
ISO/IEC 9899:201x 6.3.2.3 Pointers
- An integer may be converted to any pointer type. Except as previously specified, the result is implementation-defined, might not be correctly aligned, might not point to an entity of the referenced type, and might be a trap representation.
so you're better off passing a separate pointer to each thread.
Here's a full working example, which passes each thread a pointer to a separate element in an array:
#include <pthread.h>
#include <stdio.h>
void * collector(void* arg)
{
int* a = (int*)arg;
printf("%d\n", *a);
return NULL;
}
int main()
{
int i, id[10];
pthread_t thread_tid[10];
for(i = 0; i < 10; i++) {
id[i] = i;
pthread_create(&thread_tid[i], NULL, collector, (void*)(id + i));
}
for(i = 0; i < 10; i++) {
pthread_join(thread_tid[i], NULL);
}
return 0;
}
There's a nice intro to pthreads here.
Solution 2:
int is 32 bit, and void * is 64 bit in 64bit Linux; In that case you should use long int instead of int;
long int i;
pthread_create(&thread_id, NULL, fun, (void*)i);
int fun(void *i) function
long int id = (long int) i;
Solution 3:
void *foo(void *i) {
int a = *((int *) i);
free(i);
}
int main {
int *arg = (char*)malloc(sizeof(char))
pthread_create(&thread, 0, foo, arg);
}
Solution 4:
It better to use of a struct
for send more parameters in one :
struct PARAMS
{
int i;
char c[255];
float f;
} params;
pthread_create(&thread_id, NULL, fun, (void*)(¶ms));
then you can cast
params
to PARAMS*
and use of it in pthread
routine
:
PARAMS *p = static_cast<PARAMS*>(params);
p->i = 5;
strcpy(p->c, "hello");
p->f = 45.2;