Reputation: 274
I am trying to create threads with the pthread library. Compilation is fine with gcc -o -pthread file file.c
but when I run the code, I get a segmentation fault. I am not sure what the problem is. I tried to execute the code that was given in the textbook to try and learn but I am lost right now. Can anyone help? The code is below... very basic, yes but please hlep me out.
#include<stdio.h>
#include<pthread.h>
int sum;
void *runner(void *param);
int main (int argc, char *argv[])
{
pthread_t tid;
pthread_attr_t attr;
//printf("Am I here..?\n");
if (argc!=2)
{
fprintf(stderr, "usage: a.out ...\n");
return -1;
}
if (atoi(argv[1] < 0))
{
fprintf(stderr, "%d must be >= 0\n", atoi(argv[1]));
return -1;
}
pthread_attr_init(&attr);
pthread_create(&tid, &attr, runner, argv[1]);
pthread_join(tid, NULL);
printf("sum = %d\n", sum);
}
void *runner(void *param)
{
extern int sum;
int i, upper=atoi(param);
sum=0;
for(i=1; i<= upper; i++)
sum+=i;
pthread_exit(0);
}
Upvotes: 0
Views: 162
Reputation: 206899
Please turn on, and examine carefully, your compiler's warnings.
You're not including stdlib.h
, so atoi
is undeclared, and you're not return
ing anything from runner
but you've declared it as returning a void*
.
But the main problem is this line:
if (atoi(argv[1] < 0))
argv[1] < 0
will evaluate to 0
or 1
, which are not what you want as an argument to atoi
. What you wanted is:
if (atoi(argv[1]) < 0)
It's more than likely that your compiler would have indicated all these problems if the right warnings were enabled.
Upvotes: 3
Reputation: 121427
You have misplaced the bracket:
Change:
if (atoi(argv[1] < 0))
to:
if (atoi(argv[1]) < 0)
Upvotes: 1