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;
}
這段代碼描述了一個簡單的服務(wù)程序,為了簡化我們省略了服務(wù)的處理邏輯,也就是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),程序結(jié)束,但有可能(應(yīng)該說大多數(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ù)必須是指針類型的,因為我們需要檢測到它的實時值,而不只是使用它傳入進來的值,相應(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,運行./test,當程序啟動之后按ctl+c,看程序是不是很快就退出了。
其實這種退出并不是立馬退出,而是將sleep的等待時間分成了更小的時間片,上例是0.1秒,也就是說在按下ctr+c之后,程序其實還會延時0到0.1秒才會退出,只不過這個時間很短,看上去就像立馬退出一樣。
用條件變量實現(xiàn)sleep
大致的思想就是,在循環(huán)時等待一個條件變量,并設(shè)置超時時間,如果在這個時間之內(nèi)有其它線程觸發(fā)了條件變量,等待會立即退出,否則會一直等到設(shè)置的時間,這樣就可以通過對條件變量的控制來實現(xiàn)sleep,并且可以在需要的時候立馬退出。
條件變量往往會和互斥鎖搭配使用,互斥鎖的邏輯很簡單,如果一個線程獲取了互斥鎖,其它線程就無法獲取,也就是說如果兩個線程同時執(zhí)行到了pthread_mutex_lock語句,只有一個線程會執(zhí)行完成,而另一個線程會阻塞,直到有線程調(diào)用pthread_mutex_unlock才會繼續(xù)往下執(zhí)行。所以我們往往在多線程訪問同一內(nèi)存區(qū)域時會用到互斥鎖,以防止多個線程同時修改某一塊內(nèi)存區(qū)域。本例用到的函數(shù)有如下幾個,互斥鎖相關(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ù)功能分別是初始化、超時等待條件變量、觸發(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,主要關(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一樣,編譯之后運行,程序每隔5秒在屏幕打印一行輸出,輸入ctr+c,程序會立馬退出