C語言封裝執行緒與日誌類

2021-07-11 18:45:46 字數 3290 閱讀 3056

折騰了兩天,查半天資料還是不如自己動動手。如題這是兩個很常見的問題,雖然很多語言都封裝了執行緒,但是讓自己寫乙個還是比較麻煩的,這兒做乙個簡單的demo,大家可以去完善。

//日誌工具包

#define max_msg_text 1024*10

#define max_msg_title 1024

//日誌訊息結構體

struct logmessage

;//訊息佇列,使用到了stl的佇列

class clogqueue

;//簡單的執行緒類 有時間再完整的封裝這個類

class wrilogapi cmythread

; virtual void execute(void)=0; //執行緒不能例項化,必須要繼承實現該函式

//獲取執行緒狀態

threadstate getthreadstate();

//執行緒操作

bool start();

bool suspend();

bool resume();

void stop();

void terminate(); //結束執行緒

};class wrilogapi cwritelog: public cmythread

; clogqueue m_loglist;

void setlevel(int level=0);

void addlog(const char *msgtext, const char *msgtype, int level = 0);

void writelog(logmessage *msg);

void execute(void);

};//執行緒函式

dword winapi threadproc(void *pmythread);

//這兒可以再封裝乙個函式,客戶端不用手動例項化日誌類,直接呼叫這個函式寫日誌

//extern "c" void wrilogapi writelog(const char *str, int level = 0);

簡單的標頭檔案大概就是這樣,實現部分如下:

logutil.cpp

#include "stdafx.h"

#include "wrilog.h"

///clogqueue//

clogqueue::clogqueue()

clogqueue::~clogqueue()

void clogqueue::lock()

void clogqueue::unlock()

logmessage *clogqueue::pop()

return res;

}void clogqueue::push(logmessage *new_value)

bool clogqueue::empty() const

int clogqueue::size()

/cmythread///

cmythread::cmythread(void)

cmythread::~cmythread(void)

void cmythread::terminate()

dword winapi threadproc(void *pmythread)

//執行緒執行完畢後這兒需要根據設定來判斷是否進行清理工作,對於執行緒類來說,執行緒執行完了類也就可以釋放了,這個隨你喜歡

return 0;

}

wrilog.cpp

// wrilog.cpp : 定義 dll 應用程式的匯出函式。

//#include "stdafx.h"

#include "direct.h"

#include "wrilog.h"

cwritelog::cwritelog(const char *plogname, const char *path)

cwritelog::~cwritelog(void)

}void cwritelog::setlevel(int level)

void cwritelog::addlog(const char *msgtext, const char *msgtype, int level)

if(msgtype && strlen(msgtype)>0)

strncpy(msg->msgtype, msgtype, strlen(msgtype));

msg->level = level;

m_loglist.push(msg);

}void cwritelog::writelog(logmessage *msg)

else

char title[256];

memset(title, 0, 256);

time_t timep;

struct tm *p;

time(&timep);

p =localtime(&timep);

strftime(title, 256, "%x.", p);

file *pfile;

if(pfile = fopen(fullpath, "a+")) }

void cwritelog::execute(void)

//這兒應該用事件處理waitforsingle..,避免浪費cpu

sleep(10);

msg = m_loglist.pop();

}}

乙個簡單的封裝就完成了,下面是demo:

cwritelog *m_plog;

m_plog = new cwritelog("監控日誌", "c:\\test\\log");

m_plog->setlevel(5);

這樣就可以呼叫了

m_plog->addlog("測試。。", "debug", cwritelog::debug);

最後是釋放:

if(m_plog)

工程在我的資源裡面。



時間與日期類封裝

在ios開發時,會經常用到一些處理時間的函式和方法,比如求當前時間,計算兩個日期差幾天,格式化現在時間與給定的秒數的時間差等。所以就整理並歸納了一些比較實用的方法。主要用到的類有 nsdate,nsdateformatter,nscalendar,nsdatecomponents,nstimeint...

多執行緒與日誌的學習

def download while true glock.acquire if len face url list 0 glock.release continue else face url face url list.pop glock.release html requests.get fa...

caffe 執行緒封裝類

test.hpp ifndef internal thread hpp define internal thread hpp include include using boost shared ptr namespace boost class internalthread virtual int...