您的位置:首页 > 其它

03.5 使用多线程完成从0加到1000

2018-03-30 10:54 288 查看
#include<stdio.h>
#include<pthread.h>
#define N 1000
void* thread_main(void *arg);
//void printids(const char *s);
int	sum = 0;
int j = 0;

int main(int argc, char *argv[]) {
pthread_t t1_id, t2_id;
int thread_param = 5;
int k = 0;
int zsum = 0;

if (pthread_create(&t1_id, NULL, thread_main, (void*)&thread_param) != 0) {
puts("pthread_create() error1");
return -1;
};
if (pthread_create(&t2_id, NULL, thread_main, (void*)&thread_param) != 0) {
puts("pthread_create() error2");
return -1;
};
pthread_join(t1_id, NULL);
pthread_join(t2_id, NULL);

//sleep(10); puts("end of main");
//主线程运行累加
while (1) {
zsum += ++k;
//printf("k = %d, zsum = %d\n", k, zsum);
if (k == N)
break;
}
printf("sum = %d\n", sum);
printf("zsum = %d\n", zsum);
return 0;
}

//运行线程
void* thread_main(void *arg) {
/*int i;
int cnt = *((int*)arg);
for (i = 0; i < cnt; i++) {
sleep(1); puts("running thread");
}*/
while (1) {
if (j >= N) {
break;
}
sum += ++j;
printf("j = %d, sum = %d\n",j, sum);

}

return NULL;
}

/*void printids(const char *s)
{
pid_t pid;
pthread_t tid;
pid = getpid();
tid = pthread_self();
printf("%s pid %u tid %u (0x%x)\n", \
s, (unsigned int)pid, (unsigned int)tid, (unsigned int)tid);
}*/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  thread
相关文章推荐