C++中自定義sleep、條件變量sleep實(shí)例
sleep的作用無(wú)需多說(shuō),幾乎每種語(yǔ)言都提供了類似的函數(shù),調(diào)用起來(lái)也很簡(jiǎn)單。sleep的作用無(wú)非是讓程序等待若干時(shí)間,而為了達(dá)到這樣的目的,其實(shí)有很多種方式,最簡(jiǎn)單的往往也是最粗暴的,我們就以下面這段代碼來(lái)舉例說(shuō)明(注:本文提及的程序編譯運(yùn)行環(huán)境為L(zhǎng)inux)
/* 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;
}
這段代碼描述了一個(gè)簡(jiǎn)單的服務(wù)程序,為了簡(jiǎn)化我們省略了服務(wù)的處理邏輯,也就是Proc函數(shù)的內(nèi)容,這里我們只是周期性的打印某條語(yǔ)句,為了達(dá)到周期性的目的,我們用sleep來(lái)實(shí)現(xiàn),每隔5秒鐘打印一次。在main函數(shù)中我們對(duì)SIGINT信號(hào)進(jìn)行了捕捉,當(dāng)程序在終端啟動(dòng)之后,如果你輸入ctr+c,這會(huì)向程序發(fā)送中斷信號(hào),一般來(lái)說(shuō)程序會(huì)退出,而這里我們捕捉到了這個(gè)信號(hào),會(huì)按我們自己的邏輯來(lái)處理,也就是調(diào)用server的Stop函數(shù)。執(zhí)行編譯命令
$ g++ test.cpp -o test -lpthread
然后在終端輸入./test運(yùn)行程序,這時(shí)程序每隔5秒會(huì)在屏幕上打印一條語(yǔ)句,按下ctl+c,你會(huì)發(fā)現(xiàn)程序并沒(méi)有立即退出,而是等待了一會(huì)兒才退出,究其原因,當(dāng)按下ctl+c發(fā)出中斷信號(hào)時(shí),程序捕捉到并執(zhí)行自己的邏輯,也就是調(diào)用了server的Stop函數(shù),運(yùn)行標(biāo)記位run_被置為false,Proc函數(shù)檢測(cè)到run_為false則退出循環(huán),程序結(jié)束,但有可能(應(yīng)該說(shuō)大多數(shù)情況都是如此)此時(shí)Proc正好執(zhí)行到sleep那一步,而sleep是將程序掛起,由于我們捕捉到了中斷信號(hào),因此它不會(huì)退出,而是繼續(xù)掛起直到時(shí)間滿足為止。這個(gè)sleep顯然顯得不夠優(yōu)雅,下面介紹兩種能快速退出的方式。
自定義sleep
在我們調(diào)用系統(tǒng)提供的sleep時(shí)我們是無(wú)法在函數(shù)內(nèi)部做其它事情的,基于此我們就萌生出一種想法,如果在sleep中能夠檢測(cè)到退出變量,那豈不是就能快速退出了,沒(méi)錯(cuò),事情就是這樣子的,通過(guò)自定義sleep,我們將時(shí)間片分割成更小的片段,每隔一個(gè)片段檢測(cè)一次,這樣就能將程序的退出延遲時(shí)間縮小為這個(gè)更小的片段,自定義的sleep如下
void sleep(int seconds, const bool* run)
{
int count = seconds * 10;
while (*run && count > 0)
{
--count;
usleep(100000);
}
}
需要注意的是,這個(gè)sleep的第二個(gè)參數(shù)必須是指針類型的,因?yàn)槲覀冃枰獧z測(cè)到它的實(shí)時(shí)值,而不只是使用它傳入進(jìn)來(lái)的值,相應(yīng)的函數(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,運(yùn)行./test,當(dāng)程序啟動(dòng)之后按ctl+c,看程序是不是很快就退出了。
其實(shí)這種退出并不是立馬退出,而是將sleep的等待時(shí)間分成了更小的時(shí)間片,上例是0.1秒,也就是說(shuō)在按下ctr+c之后,程序其實(shí)還會(huì)延時(shí)0到0.1秒才會(huì)退出,只不過(guò)這個(gè)時(shí)間很短,看上去就像立馬退出一樣。
用條件變量實(shí)現(xiàn)sleep
大致的思想就是,在循環(huán)時(shí)等待一個(gè)條件變量,并設(shè)置超時(shí)時(shí)間,如果在這個(gè)時(shí)間之內(nèi)有其它線程觸發(fā)了條件變量,等待會(huì)立即退出,否則會(huì)一直等到設(shè)置的時(shí)間,這樣就可以通過(guò)對(duì)條件變量的控制來(lái)實(shí)現(xiàn)sleep,并且可以在需要的時(shí)候立馬退出。
條件變量往往會(huì)和互斥鎖搭配使用,互斥鎖的邏輯很簡(jiǎn)單,如果一個(gè)線程獲取了互斥鎖,其它線程就無(wú)法獲取,也就是說(shuō)如果兩個(gè)線程同時(shí)執(zhí)行到了pthread_mutex_lock語(yǔ)句,只有一個(gè)線程會(huì)執(zhí)行完成,而另一個(gè)線程會(huì)阻塞,直到有線程調(diào)用pthread_mutex_unlock才會(huì)繼續(xù)往下執(zhí)行。所以我們往往在多線程訪問(wèn)同一內(nèi)存區(qū)域時(shí)會(huì)用到互斥鎖,以防止多個(gè)線程同時(shí)修改某一塊內(nèi)存區(qū)域。本例用到的函數(shù)有如下幾個(gè),互斥鎖相關(guān)函數(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ù)功能分別是初始化、加鎖、解鎖、銷毀。條件變量相關(guān)函數(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ù)功能分別是初始化、超時(shí)等待條件變量、觸發(fā)條件變量、銷毀。這里需要解釋一下pthread_cond_timedwait和pthread_cond_signal函數(shù)
pthread_cond_timedwait
這個(gè)函數(shù)調(diào)用之后會(huì)阻塞,也就是類似sleep的作用,但是它會(huì)在兩種情況下被喚醒:1、條件變量cond被觸發(fā)時(shí);2、系統(tǒng)時(shí)間到達(dá)abstime時(shí),注意這里是絕對(duì)時(shí)間,不是相對(duì)時(shí)間。它比sleep的高明之處就在第一點(diǎn)。另外它還有一個(gè)參數(shù)是mutex,當(dāng)執(zhí)行這個(gè)函數(shù)時(shí),它的效果等同于在函數(shù)入口處先對(duì)mutex加鎖,在出口處再對(duì)mutex解鎖,當(dāng)有多線程調(diào)用這個(gè)函數(shù)時(shí),可以按這種方式去理解
pthread_cond_signal
它只有一個(gè)參數(shù)cond,作用很簡(jiǎn)單,就是觸發(fā)等待cond的線程,注意,它一次只會(huì)觸發(fā)一個(gè),如果要觸發(fā)所有等待cond的縣城,需要用到pthread_cond_broadcast函數(shù),參數(shù)和用法都是一樣的
有了以上背景知識(shí),就可以更加優(yōu)雅的實(shí)現(xiàn)sleep,主要關(guān)注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一樣,編譯之后運(yùn)行,程序每隔5秒在屏幕打印一行輸出,輸入ctr+c,程序會(huì)立馬退出
上一篇:C語(yǔ)言實(shí)現(xiàn)冒泡排序算法
欄 目:C語(yǔ)言
下一篇:c語(yǔ)言實(shí)現(xiàn)一個(gè)簡(jiǎn)單日歷
本文標(biāo)題:C++中自定義sleep、條件變量sleep實(shí)例
本文地址:http://mengdiqiu.com.cn/a1/Cyuyan/3133.html
您可能感興趣的文章
- 04-02func函數(shù)+在C語(yǔ)言 func函數(shù)在c語(yǔ)言中
- 04-02c語(yǔ)言中對(duì)數(shù)函數(shù)的表達(dá)式 c語(yǔ)言中對(duì)數(shù)怎么表達(dá)
- 04-02c語(yǔ)言沒(méi)有round函數(shù) round c語(yǔ)言
- 04-02C語(yǔ)言中怎么打出三角函數(shù) c語(yǔ)言中怎么打出三角函數(shù)的值
- 01-10深入理解C++中常見(jiàn)的關(guān)鍵字含義
- 01-10使用C++實(shí)現(xiàn)全排列算法的方法詳解
- 01-10深入Main函數(shù)中的參數(shù)argc,argv的使用詳解
- 01-10APUE筆記之:進(jìn)程環(huán)境詳解
- 01-10c++中inline的用法分析
- 01-10如何尋找數(shù)組中的第二大數(shù)


閱讀排行
- 1C語(yǔ)言 while語(yǔ)句的用法詳解
- 2java 實(shí)現(xiàn)簡(jiǎn)單圣誕樹(shù)的示例代碼(圣誕
- 3利用C語(yǔ)言實(shí)現(xiàn)“百馬百擔(dān)”問(wèn)題方法
- 4C語(yǔ)言中計(jì)算正弦的相關(guān)函數(shù)總結(jié)
- 5c語(yǔ)言計(jì)算三角形面積代碼
- 6什么是 WSH(腳本宿主)的詳細(xì)解釋
- 7C++ 中隨機(jī)函數(shù)random函數(shù)的使用方法
- 8正則表達(dá)式匹配各種特殊字符
- 9C語(yǔ)言十進(jìn)制轉(zhuǎn)二進(jìn)制代碼實(shí)例
- 10C語(yǔ)言查找數(shù)組里數(shù)字重復(fù)次數(shù)的方法
本欄相關(guān)
- 04-02c語(yǔ)言函數(shù)調(diào)用后清空內(nèi)存 c語(yǔ)言調(diào)用
- 04-02func函數(shù)+在C語(yǔ)言 func函數(shù)在c語(yǔ)言中
- 04-02c語(yǔ)言的正則匹配函數(shù) c語(yǔ)言正則表達(dá)
- 04-02c語(yǔ)言用函數(shù)寫(xiě)分段 用c語(yǔ)言表示分段
- 04-02c語(yǔ)言中對(duì)數(shù)函數(shù)的表達(dá)式 c語(yǔ)言中對(duì)
- 04-02c語(yǔ)言編寫(xiě)函數(shù)冒泡排序 c語(yǔ)言冒泡排
- 04-02c語(yǔ)言沒(méi)有round函數(shù) round c語(yǔ)言
- 04-02c語(yǔ)言分段函數(shù)怎么求 用c語(yǔ)言求分段
- 04-02C語(yǔ)言中怎么打出三角函數(shù) c語(yǔ)言中怎
- 04-02c語(yǔ)言調(diào)用函數(shù)求fibo C語(yǔ)言調(diào)用函數(shù)求
隨機(jī)閱讀
- 01-10使用C語(yǔ)言求解撲克牌的順子及n個(gè)骰子
- 08-05dedecms(織夢(mèng))副欄目數(shù)量限制代碼修改
- 01-10delphi制作wav文件的方法
- 04-02jquery與jsp,用jquery
- 01-10SublimeText編譯C開(kāi)發(fā)環(huán)境設(shè)置
- 08-05DEDE織夢(mèng)data目錄下的sessions文件夾有什
- 01-11ajax實(shí)現(xiàn)頁(yè)面的局部加載
- 01-11Mac OSX 打開(kāi)原生自帶讀寫(xiě)NTFS功能(圖文
- 08-05織夢(mèng)dedecms什么時(shí)候用欄目交叉功能?
- 01-10C#中split用法實(shí)例總結(jié)