zoukankan      html  css  js  c++  java
  • TD 多线程

    1,封装pthread

    thread.h

    class Thread
    {
    public:
        Thread() : mRunning(false),mPriority(PRIORITY_NOT_SET) { }
        virtual ~Thread();
        bool start(char* name);
        bool join();
        pthread_t id();
        void yield();
        bool setPriority(int priority);
    protected:
        static void* callback(void* arg);
        virtual void run() = 0;
    private:
        pthread_t mThread;
        bool mRunning;
        int mPriority;
        static const int PRIORITY_NOT_SET = -1;
    };

    thread.cpp

    #include "thread.h"
    
    #define TAG "Thread"
    
    void* Thread::callback(void* arg)
    {
        Thread* thread = (Thread*) arg;
        thread->run();
        return NULL;
    }
    
    Thread::~Thread()
    {
        if (mRunning)
        {
        }
    }
    
    bool Thread::start(char* name)
    {
        pthread_attr_t attr;
        pthread_attr_init(&attr);
    
        //int min_priority = sched_get_priority_min(SCHED_FIFO);
        //int max_priority = sched_get_priority_max(SCHED_FIFO);
    
        if(mPriority != PRIORITY_NOT_SET)
        {
            struct sched_param priority_holder;
            priority_holder.sched_priority = mPriority;
            pthread_attr_setschedparam(&attr, &priority_holder);
        }
        pthread_attr_setschedpolicy(&attr, SCHED_FIFO);
        int ret = pthread_create((pthread_t*)&mThread, &attr, callback, this);
        pthread_setname_np(mThread,name);
        mRunning = (ret == 0);
        return mRunning;
    }
    
    bool Thread::join()
    {
        if (!mRunning)
        {
            return false;
        }
        int ret = pthread_join(mThread, NULL);
        if (ret == 0)
        {
            mRunning = false;
            return true;
        }
        return false;
    }
    
    pthread_t Thread::id()
    {
        return mThread;
    }
    
    void Thread::yield()
    {
        sched_yield();
    }
    
    bool Thread::setPriority(int priority)
    {
        int ret = 0;
        mPriority = priority;
        if(mRunning)
        {
            struct sched_param params;
            params.sched_priority = priority;
            ret = pthread_setschedparam(mThread, SCHED_FIFO, &params);
        }
        return ret == 0;
    }

    2,继承Thread,实现run函数

    class MediaView: public Thread
    {
    public:
        MediaView(SelfQueue *queue);
        ~MediaView();
    
    protected:
        void run();
    』

    3,之间在类中调用start

    start("updatefilelist");
  • 相关阅读:
    用vuex实现购物车功能
    Vue引入Jquery和Bootstrap
    emWin使用外部SRAM的方法
    (四)u-boot2013.01.01 for TQ210:《mkconfig分析》
    (三)u-boot2013.01.01 for TQ210:《mkconfig分析》
    Vmware出现报错The VMware Authorization Service is not running.之后无法上网解决
    Uva 10596
    Uva 10305
    要检测两个C文件的代码的抄袭情况
    MFC简易画图
  • 原文地址:https://www.cnblogs.com/senior-engineer/p/14079115.html
Copyright © 2011-2022 走看看