C/C++ pthread_cond_timedwait()函數使用心得

原文地址:https://blog.csdn.net/dead_g/article/details/73338960

由於工作上的事情,要用到線程之間的同步,而且有超時處理,在網上看到了使用pthread_cond_timedwait()函數和pthread_cond_wait()函數,其實2個函數都差不多,我主要是要用pthread_cond_timedwait()函數。

pthread_cond_timedwait()函數有三個入口參數:

(1)pthread_cond_t __cond:條件變量(觸發條件)

(2)pthread_mutex_t __mutex: 互斥鎖

(3)struct timespec __abstime: 等待時間(其值爲系統時間 + 等待時間)

當在指定時間內有信號傳過來時,pthread_cond_timedwait()返回0,否則返回一個非0數(我沒有找到返回值的定義);

在使用pthread_cond_timedwait()函數時,必須有三步:

1:加互斥鎖:pthread_mutex_lock(&__mutex)

2:等待:pthread_cond_timedwait(&__cond, &__mutex, &__abstime)   //解鎖->等待->加鎖

3:解互斥鎖:pthread_mutex_unlock(&__mutex)

發送信號量時,也要有三步:

1:加互斥鎖:pthread_mutex_lock(&__mutex)

2:發送:pthread_cond_signal(&__cond)

3:解互斥鎖:pthread_mutex_unlock(&__mutex)

那麼,這裏就有一個問題,等待的時候已經加上鎖了,那麼我發送的時候怎麼才能運行到發送函數呢?其實這是因爲在pthread_cond_timedwait()函數中已經對互斥鎖進行解鎖操作了,所以這個時候發送信號量是不會阻塞的。其實仔細想想,這樣不是才能保證同步嗎?(寫完代碼後考慮一下)

 

#include <stdio.h>
#include <pthread.h>
#include <string.h>
#include <unistd.h>
#include <semaphore.h>
#include <sys/time.h>
 
#define SENDSIGTIME 10
 
pthread_cond_t g_cond;
pthread_mutex_t g_mutex;
 
void thread1(void *arg)
{
    int inArg = (int)arg;
    int ret = 0;
    struct timeval now;
    struct timespec outtime;
 
    pthread_mutex_lock(&g_mutex);
 
    gettimeofday(&now, NULL);
    outtime.tv_sec = now.tv_sec + 5;
    outtime.tv_nsec = now.tv_usec * 1000;
 
    ret = pthread_cond_timedwait(&g_cond, &g_mutex, &outtime);
    //ret = pthread_cond_wait(&g_cond, &g_mutex);
    pthread_mutex_unlock(&g_mutex);
 
    printf("thread 1 ret: %d\n", ret);
 
}
 
int main(void)
{
    pthread_t id1;
    int ret;
 
    pthread_cond_init(&g_cond, NULL);
    pthread_mutex_init(&g_mutex, NULL);
 
    ret = pthread_create(&id1, NULL, (void *)thread1, (void *)1);
    if (0 != ret)
    {
	printf("thread 1 create failed!\n");
	return 1;
    }
 
    printf("等待%ds發送信號!\n", SENDSIGTIME);
    sleep(SENDSIGTIME);
    printf("正在發送信號....\n");
    pthread_mutex_lock(&g_mutex);
    pthread_cond_signal(&g_cond);
    pthread_mutex_unlock(&g_mutex);
 
 
    pthread_join(id1, NULL);
 
    pthread_cond_destroy(&g_cond);
    pthread_mutex_destroy(&g_mutex);
 
    return 0;
}


--------------------- 
作者:dead_g 
來源:CSDN 
原文:https://blog.csdn.net/dead_g/article/details/73338960 
版權聲明:本文爲博主原創文章,轉載請附上博文鏈接!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章