I’m doing some first steps with threads on Linux systems, and i have this error which occures on the base of a program that gets some n
argument and creates n
number of threads.
Here is the important part of the code:
The function the threads should run:
void* function(void* arg){ int id = (long)arg; printf("Thread #%ld created!n",id); pthread_exit(0); }
Important part of code in the main
function
int main(int argc, char **argv){ if(argc != 3){ printf("Usage: %s <num> <exp>n",argv[0]); exit(-1); } int num = atoi(argv[1]), exp = atoi(argv[2]); long i; pthread_t threads[num]; pthread_attr_t attr; printf("Creating %d threads n",num); pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr,PTHREAD_CREATE_JOINABLE); for (i = 0; i < num; i++) { pthread_create(&threads[i],&attr,function,(void*)i); } pthread_attr_destroy(&attr); for (i = 0; i < num; i++) { printf("Thread #%d is %ldn", i, threads[i]); } for (i = 0; i < num; i++) { pthread_join(threads[num], NULL); } }
Notice the last for
loop with the pthread_join
function, when i comment it out the program ends fine (exit code 0), but the output is obviously wrong since not all of the threads runs function
before the main process exits.
When i don’t comment it out i get segmentation fault (core dumped)
when trying to run using the terminal in my Linux OS and Process finished with exit code 139
when running in my IDE (CLion).
I couldn’t find anything i’ve done wrong as it’s a very basic program that shouldn’t have anything hard to find, what is the problem that causes the error?
Advertisement
Answer
You should have used pthread_join(threads[i], NULL);
instead of pthread_join(threads[num], NULL);
. Suppose, the num
is set to 4 via argument. Then threads[num]
points to 5th element of array which does not exist as you have allocated an array of only 4 elements.