欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

C++中自定義sleep、條件變量sleep實例

 更新時間:2015年03月17日 09:57:46   投稿:junjie  
這篇文章主要介紹了C++中自定義sleep、條件變量sleep實例,本文直接給出實例代碼并講解了功能作用和使用方法,需要的朋友可以參考下

sleep的作用無需多說,幾乎每種語言都提供了類似的函數(shù),調(diào)用起來也很簡單。sleep的作用無非是讓程序等待若干時間,而為了達到這樣的目的,其實有很多種方式,最簡單的往往也是最粗暴的,我們就以下面這段代碼來舉例說明(注:本文提及的程序編譯運行環(huán)境為Linux)

復制代碼 代碼如下:

/* filename: test.cpp */ 
#include <stdio.h> 
#include <unistd.h> 
#include <pthread.h> 
#include <signal.h> 
 
class TestServer 

public: 
    TestServer() : run_(true) {}; 
    ~TestServer(){}; 
 
    void Start() 
    { 
        pthread_create(&thread_, NULL, ThreadProc, (void*)this); 
    } 
    void Stop() 
    { 
        run_ = false; 
    } 
    void Wait() 
    { 
        pthread_join(thread_, NULL); 
    } 
    void Proc() 
    { 
        int count = 0; 
        while (run_) 
        { 
            printf("sleep count:%d\n", ++count); 
            sleep(5); 
        } 
    } 
 
private: 
    bool run_; 
    pthread_t thread_; 
 
    static void* ThreadProc(void* arg) 
    { 
        TestServer* me = static_cast<TestServer*>(arg); 
        me->Proc(); 
        return NULL; 
    } 
}; 
 
TestServer g_server; 
 
void StopService() 

    g_server.Stop(); 

 
void StartService() 

    g_server.Start(); 
    g_server.Wait(); 

 
void SignalHandler(int sig) 

    switch(sig) 
    { 
        case SIGINT: 
            StopService(); 
        default: 
            break; 
    } 

 
int main(int argc, char* argv[]) 

    signal(SIGINT, SignalHandler); 
    StartService(); 
    return 0; 


這段代碼描述了一個簡單的服務程序,為了簡化我們省略了服務的處理邏輯,也就是Proc函數(shù)的內(nèi)容,這里我們只是周期性的打印某條語句,為了達到周期性的目的,我們用sleep來實現(xiàn),每隔5秒鐘打印一次。在main函數(shù)中我們對SIGINT信號進行了捕捉,當程序在終端啟動之后,如果你輸入ctr+c,這會向程序發(fā)送中斷信號,一般來說程序會退出,而這里我們捕捉到了這個信號,會按我們自己的邏輯來處理,也就是調(diào)用server的Stop函數(shù)。執(zhí)行編譯命令
復制代碼 代碼如下:

$ g++ test.cpp -o test -lpthread 

然后在終端輸入./test運行程序,這時程序每隔5秒會在屏幕上打印一條語句,按下ctl+c,你會發(fā)現(xiàn)程序并沒有立即退出,而是等待了一會兒才退出,究其原因,當按下ctl+c發(fā)出中斷信號時,程序捕捉到并執(zhí)行自己的邏輯,也就是調(diào)用了server的Stop函數(shù),運行標記位run_被置為false,Proc函數(shù)檢測到run_為false則退出循環(huán),程序結束,但有可能(應該說大多數(shù)情況都是如此)此時Proc正好執(zhí)行到sleep那一步,而sleep是將程序掛起,由于我們捕捉到了中斷信號,因此它不會退出,而是繼續(xù)掛起直到時間滿足為止。這個sleep顯然顯得不夠優(yōu)雅,下面介紹兩種能快速退出的方式。

自定義sleep

在我們調(diào)用系統(tǒng)提供的sleep時我們是無法在函數(shù)內(nèi)部做其它事情的,基于此我們就萌生出一種想法,如果在sleep中能夠檢測到退出變量,那豈不是就能快速退出了,沒錯,事情就是這樣子的,通過自定義sleep,我們將時間片分割成更小的片段,每隔一個片段檢測一次,這樣就能將程序的退出延遲時間縮小為這個更小的片段,自定義的sleep如下

復制代碼 代碼如下:

void sleep(int seconds, const bool* run) 

    int count = seconds * 10; 
    while (*run && count > 0) 
    { 
        --count; 
        usleep(100000); 
    } 


需要注意的是,這個sleep的第二個參數(shù)必須是指針類型的,因為我們需要檢測到它的實時值,而不只是使用它傳入進來的值,相應的函數(shù)調(diào)用也得稍作修改,完整的代碼如下
復制代碼 代碼如下:

/* filename: test2.cpp */ 
#include <stdio.h> 
#include <unistd.h> 
#include <pthread.h> 
#include <signal.h> 
 
class TestServer 

public: 
    TestServer() : run_(true) {}; 
    ~TestServer(){}; 
 
    void Start() 
    { 
     pthread_create(&thread_, NULL, ThreadProc, (void*)this); 
    } 
 
    void Stop() 
    { 
       run_ = false; 
    } 
 
    void Wait() 
    { 
        pthread_join(thread_, NULL); 
    } 
 
    void Proc() 
    { 
        int count = 0; 
        while (run_) 
        { 
            printf("sleep count:%d\n", ++count); 
            sleep(5, &run_); 
        } 
    } 
 
private: 
    bool run_; 
    pthread_t thread_; 
 
    void sleep(int seconds, const bool* run) 
    { 
        int count = seconds * 10; 
        while (*run && count > 0) 
        { 
            --count; 
            usleep(100000); 
 
        } 
    } 
 
    static void* ThreadProc(void* arg) 
    { 
        TestServer* me = static_cast<TestServer*>(arg); 
        me->Proc(); 
        return NULL; 
    } 
}; 
 
TestServer g_server; 
 
void StopService() 

   g_server.Stop(); 

 
void StartService() 

    g_server.Start(); 
   g_server.Wait(); 

 
void SignalHandler(int sig) 

    switch(sig) 
    { 
        case SIGINT: 
            StopService(); 
        default: 
            break; 
    } 

 
int main(int argc, char* argv[]) 

    signal(SIGINT, SignalHandler); 
    StartService(); 
    return 0; 

編譯g++ test2.cpp -o test,運行./test,當程序啟動之后按ctl+c,看程序是不是很快就退出了。

其實這種退出并不是立馬退出,而是將sleep的等待時間分成了更小的時間片,上例是0.1秒,也就是說在按下ctr+c之后,程序其實還會延時0到0.1秒才會退出,只不過這個時間很短,看上去就像立馬退出一樣。

用條件變量實現(xiàn)sleep

大致的思想就是,在循環(huán)時等待一個條件變量,并設置超時時間,如果在這個時間之內(nèi)有其它線程觸發(fā)了條件變量,等待會立即退出,否則會一直等到設置的時間,這樣就可以通過對條件變量的控制來實現(xiàn)sleep,并且可以在需要的時候立馬退出。

條件變量往往會和互斥鎖搭配使用,互斥鎖的邏輯很簡單,如果一個線程獲取了互斥鎖,其它線程就無法獲取,也就是說如果兩個線程同時執(zhí)行到了pthread_mutex_lock語句,只有一個線程會執(zhí)行完成,而另一個線程會阻塞,直到有線程調(diào)用pthread_mutex_unlock才會繼續(xù)往下執(zhí)行。所以我們往往在多線程訪問同一內(nèi)存區(qū)域時會用到互斥鎖,以防止多個線程同時修改某一塊內(nèi)存區(qū)域。本例用到的函數(shù)有如下幾個,互斥鎖相關函數(shù)有

復制代碼 代碼如下:

int pthread_mutex_init(pthread_mutex_t *restrict mutex,const pthread_mutexattr_t *restrict attr); 
int pthread_mutex_lock(pthread_mutex_t *mutex); 
int pthread_mutex_unlock(pthread_mutex_t *mutex); 
int pthread_mutex_destroy(pthread_mutex_t *mutex); 

以上函數(shù)功能分別是初始化、加鎖、解鎖、銷毀。條件變量相關函數(shù)有

復制代碼 代碼如下:

int pthread_cond_init(pthread_cond_t *restrict cond, const pthread_condattr_t *restrict attr); 
int pthread_cond_timedwait(pthread_cond_t *restrict cond, pthread_mutex_t *restrict mutex, const struct timespec *restrict abstime); 
int pthread_cond_signal(pthread_cond_t *cond); 
int pthread_cond_destroy(pthread_cond_t *cond); 

以上函數(shù)功能分別是初始化、超時等待條件變量、觸發(fā)條件變量、銷毀。這里需要解釋一下pthread_cond_timedwait和pthread_cond_signal函數(shù)

復制代碼 代碼如下:

pthread_cond_timedwait

這個函數(shù)調(diào)用之后會阻塞,也就是類似sleep的作用,但是它會在兩種情況下被喚醒:1、條件變量cond被觸發(fā)時;2、系統(tǒng)時間到達abstime時,注意這里是絕對時間,不是相對時間。它比sleep的高明之處就在第一點。另外它還有一個參數(shù)是mutex,當執(zhí)行這個函數(shù)時,它的效果等同于在函數(shù)入口處先對mutex加鎖,在出口處再對mutex解鎖,當有多線程調(diào)用這個函數(shù)時,可以按這種方式去理解

pthread_cond_signal
它只有一個參數(shù)cond,作用很簡單,就是觸發(fā)等待cond的線程,注意,它一次只會觸發(fā)一個,如果要觸發(fā)所有等待cond的縣城,需要用到pthread_cond_broadcast函數(shù),參數(shù)和用法都是一樣的

有了以上背景知識,就可以更加優(yōu)雅的實現(xiàn)sleep,主要關注Proc函數(shù)和Stop函數(shù),完整的代碼如下

復制代碼 代碼如下:

/* filename: test3.cpp */ 
#include <stdio.h> 
#include <unistd.h> 
#include <pthread.h> 
#include <signal.h> 
#include <sys/time.h> 
 
class TestServer 

public: 
    TestServer() : run_(true)  
    { 
        pthread_mutex_init(&mutex_, NULL); 
        pthread_cond_init(&cond_, NULL); 
    }; 
    ~TestServer() 
    { 
        pthread_mutex_destroy(&mutex_); 
        pthread_cond_destroy(&cond_); 
    }; 
 
    void Start() 
    { 
        pthread_create(&thread_, NULL, ThreadProc, (void*)this); 
    } 
 
    void Stop() 
    { 
        run_ = false; 
        pthread_mutex_lock(&mutex_); 
        pthread_cond_signal(&cond_); 
        pthread_mutex_unlock(&mutex_); 
   } 
 
    void Wait() 
    { 
        pthread_join(thread_, NULL); 
    } 
 
    void Proc() 
    { 
        pthread_mutex_lock(&mutex_); 
        struct timeval now; 
        int count = 0; 
        while (run_) 
        { 
            printf("sleep count:%d\n", ++count); 
            gettimeofday(&now, NULL); 
            struct timespec outtime; 
            outtime.tv_sec = now.tv_sec + 5; 
            outtime.tv_nsec = now.tv_usec * 1000; 
            pthread_cond_timedwait(&cond_, &mutex_, &outtime); 
        } 
        pthread_mutex_unlock(&mutex_); 
    } 
 
private: 
    bool run_; 
    pthread_t thread_; 
    pthread_mutex_t mutex_; 
    pthread_cond_t cond_; 
 
    static void* ThreadProc(void* arg) 
    { 
        TestServer* me = static_cast<TestServer*>(arg); 
        me->Proc(); 
        return NULL; 
    } 
}; 
 
TestServer g_server; 
 
void StopService() 

    g_server.Stop(); 

 
void StartService() 

    g_server.Start(); 
    g_server.Wait(); 

 
void SignalHandler(int sig) 

    switch(sig) 
    { 
        case SIGINT: 
            StopService(); 
        default: 
            break; 
    } 

 
int main(int argc, char* argv[]) 

    signal(SIGINT, SignalHandler); 
    StartService(); 
    return 0; 

和test2.cpp一樣,編譯之后運行,程序每隔5秒在屏幕打印一行輸出,輸入ctr+c,程序會立馬退出

相關文章

  • c++ const引用與非const引用介紹

    c++ const引用與非const引用介紹

    const引用是指向const對象的引用,可以讀取ref,但不能修改所以也就有將const變量賦值給非const引用是非法的,感興趣的朋友可以了解下,或許本文對你有所幫助
    2013-01-01
  • C語言學習之柔性數(shù)組詳解

    C語言學習之柔性數(shù)組詳解

    結構體的最后一個元素允許是未知大小的數(shù)組,這就叫柔性數(shù)組。這篇文中主要為大家詳細介紹了C語言中柔性數(shù)組的相關知識,需要的可以了解一下
    2023-03-03
  • vc提示unexpected end of file found的原因分析

    vc提示unexpected end of file found的原因分析

    這篇文章主要介紹了vc提示unexpected end of file found的原因分析,給出了幾點常見錯誤原因的分析,需要的朋友可以參考下
    2015-05-05
  • C++ 中const和復合類型

    C++ 中const和復合類型

    本文給大家講述的是C++ 中比較難理解的const和復合類型,結合自己的一些經(jīng)驗,分享給大家,希望大家能夠喜歡。
    2016-02-02
  • C++ const關鍵字分析詳解

    C++ const關鍵字分析詳解

    C++中的const關鍵字的用法非常靈活,而使用const將大大改善程序的健壯性。這篇文章主要介紹了C/C++ 中const關鍵字的用法,需要的朋友可以參考下
    2021-08-08
  • 深入理解C語言指針

    深入理解C語言指針

    關于指針,其是C語言的重點,C語言學的好壞,其實就是指針學的好壞。其實指針并不復雜,學習指針,要正確的理解指針
    2020-02-02
  • C++中volatile關鍵字的使用詳解以及常見的誤解

    C++中volatile關鍵字的使用詳解以及常見的誤解

    volatile 關鍵字是一種類型修飾符,用它聲明的類型變量表示可以被某些編譯器未知的因素更改,比如:操作系統(tǒng),硬件或者其他線程等
    2020-01-01
  • C語言版五子棋游戲的實現(xiàn)代碼

    C語言版五子棋游戲的實現(xiàn)代碼

    這篇文章主要為大家詳細介紹了C語言版五子棋游戲的實現(xiàn)代碼,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2021-07-07
  • 用C語言實現(xiàn)圣誕樹(簡易版+進階版)

    用C語言實現(xiàn)圣誕樹(簡易版+進階版)

    大家好,本篇文章主要講的是用C語言實現(xiàn)圣誕樹(簡易版+進階版),感興趣的同學趕快來看一看吧,對你有幫助的話記得收藏一下,方便下次瀏覽
    2021-12-12
  • C++中vector類的一些簡單實現(xiàn)

    C++中vector類的一些簡單實現(xiàn)

    C++中的std::vector是一個動態(tài)數(shù)組(也被稱為可變大小數(shù)組)的容器類,它是C++標準庫提供的其中一種容器類,提供了方便的操作和管理動態(tài)數(shù)組的功能,本文就給大家介紹了C++中vector類的簡單實現(xiàn)代碼,需要的朋友可以參考下
    2023-08-08

最新評論