#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); }*/
03.5 使用多线程完成从0加到1000
猜你喜欢
转载自blog.csdn.net/weixin_41755681/article/details/79754373
今日推荐
周排行