Re: thread shows wrong results for calculation
- From: Eric Sosman <esosman@xxxxxxxxxxxxxxxxxxxx>
- Date: Thu, 02 Dec 2010 21:02:27 -0500
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
.
- Follow-Ups:
- References:
- thread shows wrong results for calculation
- From: John
- thread shows wrong results for calculation
- Prev by Date: thread shows wrong results for calculation
- Next by Date: thread shows wrong results for calculation
- Previous by thread: thread shows wrong results for calculation
- Next by thread: Re: thread shows wrong results for calculation
- Index(es):
Relevant Pages
|