实现NCThread功能

功能描述:定义一个类,继承NCThread 类,调用start函数就可以启动一个线程,线程调用子类的run函数

步骤:

  1. 定义父类NCThread,定义一个静态函数,函数参数为void*,这里会传该类的指针进来
  2. 父类NCThread中定义run函数,注意为virtual,这样才可以调到子类的run函数
  3. 父类NCThread定义start函数,启动一个线程,线程函数为该类中的静态函数,参数为this指针
  4. 定义子类MyThread,重写父类的run函数
#include <iostream>
#include <thread>
#include <unistd.h>
#include <atomic>

using namespace std;

std::atomic<int> global_counter (0);
void increase_global (int n) {
    for (int i=0; i<n; ++i)
        cout << ++global_counter << endl;
}

class NCThread {
public:
    static void* pthread_func(void* param) {
        NCThread *m_thread = (NCThread*)param;
        if (m_thread != nullptr) {
            m_thread->run();
        }
    }

    static void thread_func(void* param) {
        NCThread *m_thread = (NCThread*)param;
        m_thread->run();
    }
    virtual void run() {
       cout << "father:run()" << endl;
    }
    void start() {
        cout << "thread start0" << endl;
        thread t2(thread_func, (void*)this);
        t2.detach();
        cout << "thread start1" << endl;
        //pthread_create(&id, NULL, pthread_func, (void *)this);
    }
private:
    pthread_t id;
};


class MyThread : public NCThread {
public:
    void run() {
        while (1) {
            m_i++;
            cout << "time:" << m_i << endl;
            sleep(1);
        }
    }
private:
    int m_i = 0;
};

int main() {
    MyThread myThread;
    myThread.start();
    //std::thread t1(increase_global,1000);
    //t1.join();

    sleep(10);
    return -1;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章