c 執行緒安全queue佇列Logger日誌

2021-10-01 13:26:52 字數 3434 閱讀 3373

程序中單例模式logger類,第一次getinstance()進行初始化後,並啟動log輸出執行緒。

若不使用setlogfile()設定log輸出檔案,預設是標準輸出std::cout。

使用者格式化的log資訊,加鎖入隊,使用條件變數通知喚醒等待的log輸出執行緒。

log輸出執行緒中,當佇列不為空,就進行輸出到制定檔案或者std::cout,否者wait(),解鎖,直到有入隊喚醒,再次加鎖。

#pragma once

#include

#include

#include

#include

#include

#include

#include

#include

#include

#include

enum priority ;

class logger;}

#ifdef _debug

#define log_debug(fmt, ...) logger::instance().log(log_debug, __file__, __function__,__line__, fmt, ##__va_args__)

#else

#define log_debug(fmt, ...)

#endif

#define log_info(fmt, ...) logger::instance().log2(log_info, fmt, ##__va_args__)

#define log_error(fmt, ...) logger::instance().log(log_error, __file__, __function__,__line__, fmt, ##__va_args__)

class timestamp

void

reset()

int64_t elapsed()

static std:

:string localtime()

;private:

std:

:chrono:

:time_point:chrono:

:high_resolution_clock> _begintimepoint;

};

#if defined(win32) || defined(_win32) 

#ifndef _crt_secure_no_warnings

#define _crt_secure_no_warnings

#endif

#endif

#include

"logger.h"

#include

#include

#include

"timestamp.h"

const

char

* priority_to_string=

;logger:

:logger()

:_shutdown

(false)

logger& logger:

:instance()

logger::~

logger()

void logger:

:setlogfile

(char

*pathname)

}void logger:

:log

(priority priority,

const

char

* __file,

const

char

* __func,

int __line,

const

char

*fmt,..

.);sprintf

(buf,

"[%s][%s:%s:%d] "

, priority_to_string[priority]

, __file, __func, __line)

; va_list args;

va_start

(args, fmt)

;vsprintf

(buf +

strlen

(buf)

, fmt, args)

;va_end

(args)

; std:

:string entry

(buf)

; std:

:unique_lock:mutex>

lock

(_mutex)

; _queue.

push

(std:

:move

(entry));

lock.

unlock()

;

_cond.

notify_all()

;}void logger:

:log2

(priority priority,

const

char

*fmt,..

.);sprintf

(buf,

"[%s] "

, priority_to_string[priority]

);

va_list args;

va_start

(args, fmt)

;vsprintf

(buf +

strlen

(buf)

, fmt, args)

;va_end

(args)

; std:

:string entry

(buf)

; std:

:unique_lock:mutex>

lock

(_mutex)

; _queue.

push

(std:

:move

(entry));

lock.

unlock()

;

_cond.

notify_all()

;}void logger:

:run()

else}}

std:

:string timestamp:

:localtime()

; std:

:string timestring;

std:

:strftime

(buffer,

200,

"%f %t"

, std:

:localtime

(&tt));

stream << buffer;

#endif

return stream.

str();

}

python執行緒佇列 queue

queue佇列 使用import queue,用法與程序queue一樣 用法介紹 classqueue.queue maxsize 0 先進先出 import queue q queue.queue q.put first q.put second q.put third print q.get p...

執行緒安全的queue

include stdafx.h include include include include include using namespace std struct datablock class cdataqueue close the event handle cdataqueue publi...

C 優先佇列Queue

1.入隊,如例 q.push x 將x 接到佇列的末端。2.出隊,如例 q.pop 彈出佇列的第乙個元素,注意,並不會返回被彈出元素的值。3.訪問隊首元素,如例 q.front 即最早被壓入佇列的元素。4.訪問隊尾元素,如例 q.back 即最後被壓入佇列的元素。5.判斷佇列空,如例 q.empty...