c - Trying to understand POSIX Threads -
i trying grasp on use of posix threads , created simple program increments global variable 10. on runs way through fine, other seg faults in random spots. while type of issue seems regular thing threads, cannot understand why happens in such simple example. current thought maybe parent ending before due not joining threads, if try join seg fault on first thread... join statement left in commented out. join used in correct syntax? not preforming join leading seg fault?
#include <stdio.h> #include <stdlib.h> #include <pthread.h> #include <errno.h> #include <string.h> #define numphilo 5 thread_t threads[numphilo]; //array of threads pthread_mutex_t mutex; // initialize mutex int x = 5; //for test int y = 10; int philofunct(){ pthread_mutex_lock (&mutex); x = x+y; pthread_mutex_unlock (&mutex); printf("philo fucntion x = %d\n",x); return x; } int main(){ pthread_mutex_init(&mutex, null); for(int = 0; < numphilo; i++){ printf("creating thread[%i]\n",i); if( pthread_create(&threads[i], null, (void *)philofunct(),(void *) &i) != 0) fprintf(stderr, "%s", strerror(errno)); // pthread_join(threads[i],null); // printf("threads joined\n"); } pthread_mutex_destroy(&mutex); printf("threads created\n"); }
output:
creating thread[0] philo fucntion x = 15 creating thread[1] philo fucntion x = 25 creating thread[2] philo fucntion x = 35 creating thread[3] philo fucntion x = 45 creating thread[4] philo fucntion x = 55 threads created
next time ran:
creating thread[0] philo fucntion x = 15 creating thread[1] philo fucntion x = 25 creating thread[2] philo fucntion x = 35 segmentation fault (core dumped)
as always, appreciated.
the main problem have here:
if( pthread_create(&threads[i], null, (void *)philofunct(),(void *) &i) != 0)
look carefully, calling philofunct()
instead of passing function pointer it. worse, passing return value of philofunct()
, integer such 15
, function pointer pthread_create()
. naturally, thread segv when tries execute code address such 15
.
once define philofunct()
correctly this:
void *philofunct(void *arg)
you can call pthread_create()
without cast:
if( pthread_create(&threads[i], null, philofunct,(void *) &i) != 0)
also, if want join threads, should join threads after running. if join thread in creation loop, waiting each thread finish before creating next one. write this:
for (i=0;i<numphilo; i++) { pthread_create(&threads[i], ...); // other stuff... } (i=0;i<numphilo; i++) pthread_join(threads[i], null);
Comments
Post a Comment