What are you doing:
check = pthread_create( &tid[i], NULL, tFunction,
(void *) 4
);
And considering the 4th argument as int *
, which obviously is not there. When you tFunction
address 4 in tFunction
, you get segfault.
If you want to pass a pointer to an int
with a value of 4, pass the address of the int
variable, that is:
#include <pthread.h> #define CONSTANT 4 void * tFunction ( void * param ) { int num = * (int *) param; /* Seg fault line */ } int main(void) { int arg = CONSTANT; pthread_t tid[CONSTANT]; int i, check; for( i = 0; i < CONSTANT; i++ ) { check = pthread_create( &tid[i], NULL, tFunction, (void *) &arg ); } return 0; }
EDIT : pthread_join
will be useful, so you can wait for your threads to finish before exiting your program.
EDIT2 . If you haven’t read the comments yet: you must make sure that if your transfer is a local variable (as in this example, which had to show very minor changes in its code in order to get it working), that any new threads end before the variable goes out of scope using pthread_join
or dynamically allocates memory for a variable on the heap.
source share