实现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;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值