- 论坛徽章:
- 1
|
先把问题修正完,后面是代码,楼主测测看。
1. kk = z * z /kk + kk;
kk开始为0, 会马上产生除0错。
2. 楼主未见kk除0错,实际上被优化掉了, for(int z = 0; z < count; z++) 没有意义
3. mutex未初始化
4. if(err=0)
- #include <stdio.h>
- #include <string.h>
- #include <strings.h>
- #include <stdlib.h>
- #include <pthread.h>
- int count = 1000000;
- volatile int k = 0;
- pthread_mutex_t mutex;
- void *thr_fn(void *arg)
- {
- volatile int tmp;
- pthread_detach(pthread_self());
- pthread_mutex_lock(&mutex);
- k++;
- tmp = k;
- pthread_mutex_unlock(&mutex);
- int kk = 0;
- for(int z = 0; z < count; z++)
- {
- kk = z * z /(kk == 0 ? 1 : kk) + kk; //避免除0错
- }
- printf("kk = %d, ", kk); //加上这句,防止kk被当作无用物品(优化掉)
- printf("%05d end pid:%u tid:%u\n", tmp, getpid(), pthread_self());
- printf("xxx\n");
- pthread_exit(0);
- printf("xxx\n");
- return NULL;
- }
- int main()
- {
- int err;
- int i = 0;
- pthread_t tid = 0;
- pthread_mutex_init(&mutex, NULL); //加上初始化
- for(; i < 10000; i++)
- {
- printf("i = [%d]\n", i);
- err = pthread_create(&tid,NULL,thr_fn, NULL);
- if(err!=0) // ==不能写错
- {printf("can't create thread:%s\n",strerror(err));
- return 0;
- }
- }
- sleep(100);
-
- //exit之前,最好加上保证线程已退出的代码
-
- exit(0);
- }
复制代码 |
|