Re: thread shows wrong results for calculation



On 12/2/2010 8:57 PM, John wrote:
Hi,

I have a program that creates a thread and takes a struct as an
argument. The child process uses the values from the struct in a
calculation and then the child prints the results. The results have
been all over the place. Sometimes I get the correct results for the
first couple of loops, after that the results go wrong. Here is some
of the code:

struct thread_data{
unsigned long linecount;
unsigned long linecounter;
};

struct thread_data my_thread;

static void *PrintResults (void *threadarg) {
struct thread_data *threaddata;
unsigned long linec;
unsigned long finall;
unsigned long calc;

threaddata = (struct thread_data *) threadarg;

while (1) {
sleep(7);
linec = threaddata->linecounter;
finall = threaddata->finallinecount;
calc = 100 * linec / finall;
printf("%lu%%\n", calc);
printf("linec = %lu\n",linec);
printf("final = %lu\n",finall);
fflush(stdout);
}
pthread_exit(NULL);
}

int main(int argc, char **argv) {
pthread_t threads;
int ret=0;

ret = pthread_create(&threads, NULL, PrintStatus, (void *)
&my_thread);
if (ret != 0){
printf("pthread_create error is %d\n", ret);
exit(EXIT_FAILURE);
}
pthread_detach(threads);

This is some of the results:
2%
linec = 6859670
final = 308915776
4%
linec = 13722593
final = 308915776
6%
linec = 20584196
final = 308915776
8%
linec = 27452927
final = 308915776
11%
linec = 34320168
final = 308915776
13%
linec = 41188633
final = 308915776
1%
linec = 48055883
final = 308915776


What am I doing wrong?

Possibly something in the PrintStatus() function that you
didn't show us?

--
Eric Sosman
esosman@xxxxxxxxxxxxxxxxxxxx
.



Relevant Pages

  • Re: thread shows wrong results for calculation
    ... I have a program that creates a thread and takes a struct as an ... The child process uses the values from the struct in a ... unsigned long linec; ... int main{ ...
    (comp.unix.programmer)
  • Re: thread shows wrong results for calculation
    ... I have a program that creates a thread and takes a struct as an ... The child process uses the values from the struct in a ... unsigned long linec; ... int main{ ...
    (comp.unix.programmer)
  • thread shows wrong results for calculation
    ... I have a program that creates a thread and takes a struct as an ... The child process uses the values from the struct in a ... unsigned long linec; ... int main{ ...
    (comp.unix.programmer)
  • thread shows wrong results for calculation
    ... I have a program that creates a thread and takes a struct as an ... The child process uses the values from the struct in a ... unsigned long linec; ... int main{ ...
    (comp.unix.programmer)
  • Re: waitpid query
    ... I.e. you're learning C as a side effect of exploring Unix systems programming. ... struct sigaction myaction; ... Because that's the behavior of waitpid in your operating system's kernel. ... child process, so the dead child remains pending. ...
    (comp.lang.c)