线程同步技术
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
int pthread_mutex_lock(pthread_mutex_t *mutex);
int pthread_mutex_unlock(pthread_mutex_t *mutex);
void *func(void *arg) { int *a = (int *)arg; printf("thread%d start\n", *a); int i; for(i=0;i<10;i++) { printf("thread%d is running\n", *a); sleep(1); } printf("thread%d end\n", *a); pthread_exit(NULL); } int main(int arg, char * args[]) { printf("process start\n"); pthread_t thr_d1, thr_d2; int i[2]; i[0] = 1; i[1] =2; pthread_create(&thr_d1, NULL, func, &i[0]); pthread_create(&thr_d2, NULL, func, &i[1]); pthread_join(thr_d1, NULL); pthread_join(thr_d2, NULL); printf("process end\n"); return 0; }
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; void *func(void *arg) { pthread_mutex_lock(&mutex); int *a = (int *)arg; printf("thread%d start\n", *a); int i; for(i=0;i<10;i++) { printf("thread%d is running\n", *a); sleep(1); } printf("thread%d end\n", *a); pthread_mutex_unlock(&mutex); pthread_exit(NULL); } int main(int arg, char * args[]) { printf("process start\n"); pthread_t thr_d1, thr_d2; int i[2]; i[0] = 1; i[1] =2; pthread_create(&thr_d1, NULL, func, &i[0]); pthread_create(&thr_d2, NULL, func, &i[1]); pthread_join(thr_d1, NULL); pthread_join(thr_d2, NULL); printf("process end\n"); return 0; }
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。