互斥锁Demo
#include <stdio.h> #include <pthread.h> pthread_t work1Id; pthread_t work2Id; int work1Ret = 1; int work2Ret = 2; pthread_cond_t cond_ready = PTHREAD_COND_INITIALIZER; pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; int number = 0; void* Work1(void* args) { int i = 0; printf("I am work%d\n", *((int*)args)); for(i = 0; i < 10; i++) { pthread_mutex_lock(&mutex); number++; if(number%2==0) { printf("I am work%d, Finish\n", *((int*)args)); pthread_cond_signal(&cond_ready); sleep(1); } pthread_mutex_unlock(&mutex); printf("I am work%d, number = %d and unlock \n", *((int*)args), number); sleep(1); } return &work1Ret; } void* Work2(void* args) { printf("I am work%d\n", *((int*)args)); while(number <10) { pthread_mutex_lock(&mutex); if(number <= 10) { pthread_cond_wait(&cond_ready, &mutex); printf("I am work%d, number = %d receive SIG\n", *((int*)args), number); } pthread_mutex_unlock(&mutex); } return &work2Ret; } int main() { int args1 = 1; int args2 = 2; void* work1Ret = NULL; void* work2Ret = NULL; pthread_create(&work1Id, NULL, Work1, &args1); pthread_create(&work2Id, NULL, Work2, &args2); pthread_join(work1Id, &work1Ret); if(work1Ret != NULL) { printf("work1Ret = %d\n", *((int*)work1Ret)); } pthread_join(work2Id, &work2Ret); if(work2Ret != NULL) { printf("work2Ret = %d\n", *((int*)work2Ret)); } return 0; }