C++写得统计线程利用率的小工具

thread_usage.h
#ifndef __THREAD_USAGE__
#define __THREAD_USAGE__

#include <fstream>
#include <string>
#include <map>
#include <pthread.h>

namespace thread
{
class CThreadUsage
{
public:
    CThreadUsage(unsigned int printCount, std::string strFilename);
    ~CThreadUsage();

    void AddThread(pthread_t pthread_id);
    void Add();
    void Print();
    void Clear();
private:  
    std::map<pthread_t, int> usage_;
    unsigned int printCount_;
    std::ofstream output_;
    unsigned int count_;
    pthread_mutex_t mutex_;
    
};


}

#endif //__THREAD_USAGE__


thread_usage.cpp

#include "thread_usage.h"

using namespace thread;

CThreadUsage::CThreadUsage(unsigned int printCount, std::string strFilename)
    :printCount_(printCount),
     output_(strFilename.c_str()),
     count_(0)
{
    pthread_mutex_init(&mutex_, NULL);
}

CThreadUsage::~CThreadUsage()
{
    output_.close();
    pthread_mutex_destroy(&mutex_);
}

void CThreadUsage::AddThread(pthread_t pthread_id)
{
    pthread_mutex_lock(&mutex_);
    usage_.insert(std::make_pair<pthread_t, int>(pthread_id, 0));//将每个线程的线程ID加入map.
    pthread_mutex_unlock(&mutex_);
}

void CThreadUsage::Add()
{
    pthread_mutex_lock(&mutex_);
    ++usage_[pthread_self()];
    ++count_;
    if (printCount_ == count_)
    {
        Print();//打印
        Clear();//清空
    }    
    pthread_mutex_unlock(&mutex_);
}

void CThreadUsage::Print()
{
    output_ << "========== Begin ========" << "\n"
            << "Thread_ID\t" << "Usage" << std::endl;

    for (std::map<pthread_t, int>::iterator iBegin = usage_.begin();
         iBegin != usage_.end(); ++iBegin)
    {
        output_ << iBegin->first << "\t" << iBegin->second << std::endl;
    }
    output_ << "=========== End =========" << std::endl;
}

void CThreadUsage::Clear()
{
    count_ = 0;
    for (std::map<pthread_t, int>::iterator iBegin = usage_.begin();
         iBegin != usage_.end(); ++iBegin)
    {
        iBegin->second = 0;
    }
}


测试函数:

#include "thread_usage.h"

thread::CThreadUsage oThreadUsage(100, "num.txt");//每处理完100个线程,就打印一次每个线程处理的任务数量

void* pthread_func(void* argv)
{
    pthread_detach(pthread_self());
    oThreadUsage.AddThread(pthread_self());
    while (1)
    {
        oThreadUsage.Add();
        sleep(1);
    }
    return NULL;
}

int main()
{
    pthread_t thread[10];
    
    for (int iIndex = 0; iIndex < 10; ++iIndex)
    {
        pthread_create(&thread[iIndex], NULL, pthread_func, NULL);
    }

    while(1);
}


郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。