#include <pthread.h> #include <stdio.h> /* this function is run by the first thread */ void *inc_x(void *x_void_ptr) { printf("线程XXXXXXXXXXXXXXXXXXXXXXX开始\n"); /* increment x to 100 */ int *x_ptr = (int *)x_void_ptr; while(++(*x_ptr) < 100){ printf("线程X: %d\n", *x_ptr); } printf("线程XXXXXXXXXXXXXXXXXXXXXXX结束\n"); /* the function must return something - NULL will do */ return NULL; } /* this function is run by the second thread */ void *inc_y(void *y_void_ptr) { printf("线程YYYYYYYYYYYYYYYYYYYYYY开始\n"); /* increment x to 100 */ int *y_ptr = (int *)y_void_ptr; while(++(*y_ptr) < 100){ printf("线程Y: %d\n", *y_ptr); } printf("线程YYYYYYYYYYYYYYYYYYYYYY结束\n"); /* the function must return something - NULL will do */ return NULL; } int main() { int x = 0, y = 0; /* show the initial values of x and y */ printf("x: %d, y: %d\n", x, y); /* this variable is our reference to the first thread */ pthread_t inc_x_thread; /* this variable is our reference to the second thread */ pthread_t inc_y_thread; /* create a first thread which executes inc_x(&x) */ if(pthread_create(&inc_x_thread, NULL, inc_x, &x)) { fprintf(stderr, "Error creating thread\n"); return 1; } /* create a second thread which executes inc_x(&x) */ if(pthread_create(&inc_y_thread, NULL, inc_y, &y)) { fprintf(stderr, "Error creating thread\n"); return 1; } /* wait for the second thread to finish */ if(pthread_join(inc_x_thread, NULL)) { fprintf(stderr, "Error joining thread\n"); return 2; } if(pthread_join(inc_y_thread, NULL)) { fprintf(stderr, "Error joining thread\n"); return 2; } /* show the results - x is now 100 thanks to the second thread */ printf("x: %d, y: %d\n", x, y); return 0; }
C - pthread多线程最简单示例
原创
©著作权归作者所有:来自51CTO博客作者2241728500的原创作品,请联系作者获取转载授权,否则将追究法律责任
上一篇:C打印二进制函数
提问和评论都可以,用心的回复会被更多人看到
评论
发布评论
相关文章
-
做软件测试需要懂代码吗?
如果想要追求月薪20k、30k,接口、自动化等是避免不了的,这就必然涉及到了代码层面。
测试人员 自动化测试 开发人员 -
线程池代码与测试
代码】线程池代码与测试。
java 算法 大数据 spring ide