本人照着《高级linux程序设计》的第4章 4.1.3线程返回值
列表 4.4 (primes.c) 在线程中计算质数
敲出如下代码:(在虚拟机下的ubunut环境测试)
1 #include <pthread.h>
2 #include <stdio.h>
3 /*(非常低效地)计算连续的质数。返回第N个质数。N是由 *ARG 指向的参数。*/
4 void* computer_prime(void* arg)
5 {
6 int candidate = 2;
7 int n = *( (int*)arg );
8 while(1)
9 {
10 int factor;
11 int is_prime = 1;
12 fprintf(stderr,"the arg is %d /n",*((int*) arg));
13 fprintf(stderr,"the n is %d /n",n);
14 /*用连续除法检测是否为质数。*/
15 for(factor = 2; factor<candidate; ++factor)
16 if(candidate%factor == 0)
17 {
18 is_prime = 0;
19 break;
20 }
21
22
23 if(is_prime)
24 {
/*这个质数是我们寻找的么? */
25 if(--n ==0)
/*将所求的质数作为线程返回值传回。*/
26 return (void*)candidate;
27 }
28
29
30 ++candidate;
31
32 }
33
34
35 return NULL;
36 }
37
38 int main()
39 {
40 pthread_t thread;
41
42 /* int test = 50;*/
43
44 int which_prime = 50;
45
46 *为什么没有下面的定义int test 时 最后的which_prime会为0??是对齐的问题吗*/
47
/*而且为什么在上面定义test,test最后输出正确,which_prime却为0;*/
/*而在下面定义test时,最后which_prime输出正确,而test却为0呢??*/
/*输出在64 和 67段*/
48
49 int test = 50 ;
50 int prime;
51
52 /*开始计算线程,求取第which_prime个质数。*/
53 pthread_create(&thread, NULL,&computer_prime, &which_prime);
54
/*other job*/
55 printf("I am working here together /n");
56
57 printf("the witch_prime is %d /n",which_prime);
58
59 /*waiting for the over of tread*/
/*等待计算线程的结束,并且取得结果。*/
60 pthread_join(thread, (void*)&prime);
61
62
63 /*why ???????????*/
64 printf("the test is %d /n",test);
65
66 /*输出所求得的最大质数。*/
67 printf("the %d th prime number is %d /n ",which_prime,prime);
68
69 printf("I am working here together /n");
70 return 0;
71 }
请问:是位对齐的问题吗??我该怎么调试才可以找出真正的答案呢??