zoukankan      html  css  js  c++  java
  • 线程维护日志队列

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

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

    代码很简单,如下:

    //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
    ", 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;
    }
  • 相关阅读:
    Dll版本管理
    线程池ThreadPool
    关于sitemesh和freemark在struts2中的一些问题总结
    Google 怎么搜索
    android 设计模式
    android webview
    ios 基础数据类型
    android 常用
    android Handler vs Timer
    网站
  • 原文地址:https://www.cnblogs.com/lichmama/p/3919458.html
Copyright © 2011-2022 走看看