linux回調函數的使用

#include<stdio.h>
#include<pthread.h>
#include<unistd.h>
pthread_mutex_t mutex;
pthread_cond_t cond;
void *child1 (void *arg)
{
 pthread_cleanup_push((void *)pthread_mutex_unlock,(void *)&mutex);//註釋1
 while(1)
 {printf("thread1 get running \n");
  printf("thread1 pthread_mutex_lock returns %d\n",pthread_mutex_lock(&mutex));
  pthread_cond_wait(&cond,&mutex);
  printf("thread1 condition applied\n");
  pthread_mutex_unlock(&mutex);
  sleep(5);
  }
 pthread_cleanup_pop(0);//註釋2
}
void *child2 (void *arg)
{
 while(1)
 {sleep(3);//註釋3
  printf("thread2 get running \n");
  printf("thread2 pthread_mutex_lock returns %d\n",pthread_mutex_lock(&mutex));
  pthread_cond_wait(&cond,&mutex);
  printf("thread2 condition applied\n");
  pthread_mutex_unlock(&mutex);
  sleep(1);
  }
}
int main()
{pthread_t tid1,tid2;
 printf("hello condition variable test\n");
 pthread_mutex_init(&mutex,NULL);
 pthread_cond_init(&cond,NULL);
 pthread_create(&tid1,NULL,child1,NULL);
 pthread_create(&tid2,NULL,child2,NULL);
 do{
    sleep(2);//註釋4
    pthread_cancel(tid1);//註釋5
    sleep(2);//註釋6
    pthread_cond_signal(&cond);
    }while(1);
    sleep(100);
    pthread_exit(0);
    return 0;
}

若是不執行註釋5的pthread_cancle()動做,那麼即便沒有sleep()延時操做,child1和child都能正常工做。註釋3和
註釋4的延遲使child1有時間完成取消動做,使child2能在child1退出後執行請求鎖操做。若是沒有註釋1和註釋2的
回調函數的定義,則系統將掛起在child2請求鎖的地方;若是不作註釋3也不作註釋4的延時,則child2能在child1
完成取消動做以前獲得控制,從而順利執行申請鎖的操做,但卻可能在child_cond_wait()中掛起,由於其中也有申請
mutex的操做。child1函數給出的是標準的條件變量的使用方式:回調函數保護,等待條件前鎖定,child_cond_wait()
返回後解鎖。條件變量機制不是異步信號安全的,也就是說,在信號處理函數中調用pthread_cond_signal()或
pthread_cond_broadcast()極可能引發死鎖!!安全

程序運行結果爲:app

能夠看出最後一直在執行線程2,由於線程1被取消了!                         這就是要加-lpthread的緣由!!
 
相關文章
相關標籤/搜索