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ì)立馬退出
相關(guān)文章
C語(yǔ)言學(xué)習(xí)之柔性數(shù)組詳解
結(jié)構(gòu)體的最后一個(gè)元素允許是未知大小的數(shù)組,這就叫柔性數(shù)組。這篇文中主要為大家詳細(xì)介紹了C語(yǔ)言中柔性數(shù)組的相關(guān)知識(shí),需要的可以了解一下2023-03-03vc提示unexpected end of file found的原因分析
這篇文章主要介紹了vc提示unexpected end of file found的原因分析,給出了幾點(diǎn)常見(jiàn)錯(cuò)誤原因的分析,需要的朋友可以參考下2015-05-05C++中volatile關(guān)鍵字的使用詳解以及常見(jiàn)的誤解
volatile 關(guān)鍵字是一種類型修飾符,用它聲明的類型變量表示可以被某些編譯器未知的因素更改,比如:操作系統(tǒng),硬件或者其他線程等2020-01-01用C語(yǔ)言實(shí)現(xiàn)圣誕樹(shù)(簡(jiǎn)易版+進(jìn)階版)
大家好,本篇文章主要講的是用C語(yǔ)言實(shí)現(xiàn)圣誕樹(shù)(簡(jiǎn)易版+進(jìn)階版),感興趣的同學(xué)趕快來(lái)看一看吧,對(duì)你有幫助的話記得收藏一下,方便下次瀏覽2021-12-12C++中vector類的一些簡(jiǎn)單實(shí)現(xiàn)
C++中的std::vector是一個(gè)動(dòng)態(tài)數(shù)組(也被稱為可變大小數(shù)組)的容器類,它是C++標(biāo)準(zhǔn)庫(kù)提供的其中一種容器類,提供了方便的操作和管理動(dòng)態(tài)數(shù)組的功能,本文就給大家介紹了C++中vector類的簡(jiǎn)單實(shí)現(xiàn)代碼,需要的朋友可以參考下2023-08-08