#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; }
时间: 2024-11-23 14:31:30