线程维护日志队列

本文介绍了一种利用多线程技术实现的日志输出方法。该方法通过业务线程向日志队列添加日志节点,并由专门的副线程负责消费队列中的日志,有效避免了因日志输出造成的线程阻塞问题。

基本概念就是,业务线程输出日志(主要是增加日志队列节点),然后副线程负责日志队列的消耗。

这样做的好处就是不会因为日志输出而造成线程阻塞。

代码很简单,如下:

//code by lichmama from cnblogs.com
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <windows.h>
#include <process.h>

struct _log_ {
    int log_type;
    int log_length;
    char log_text[1024];
};

typedef struct _log_queue_ {
    struct _log_ log;
    struct _log_queue_ *next;
}LOG_QUEUE, *PLOG_QUEUE;

HANDLE hmutex = NULL;
PLOG_QUEUE head = NULL;
PLOG_QUEUE tail = NULL;
PLOG_QUEUE temp = NULL;
PLOG_QUEUE ttmp = NULL;

unsigned  int __stdcall log_thread(void *args){
    for(;;){
        WaitForSingleObject(hmutex, INFINITE);
        if(head){
            ttmp = head;
            printf("%03d, %d, %s\n", ttmp->log.log_type, ttmp->log.log_length, ttmp->log.log_text);
            head = head->next;
            if(!head)tail = NULL;
            free(ttmp);
            ttmp = NULL;
        }
        ReleaseMutex(hmutex);
    }
    return 0;
}

int main(){
    HANDLE hmutex = CreateMutex(NULL, TRUE, NULL);
    HANDLE hthread = _beginthreadex(NULL, 0, log_thread, NULL, 0, NULL);
    char ch;
    while((ch=getch())!='q'){
        temp = (PLOG_QUEUE)malloc(sizeof(LOG_QUEUE));
        temp->log.log_type = ch-'0';
        temp->log.log_length = 11;
        strcpy(temp->log.log_text, "hello,world");
        temp->next = NULL;
        if(!head)tail = temp, head = temp;
        else tail->next = temp, tail = temp;
    }
    CloseHandle(hmutex);
    TerminateThread(hthread, 0);
    CloseHandle(hthread);
    return 0;
}

 

转载于:https://www.cnblogs.com/lichmama/p/3919458.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值