功能描述:定義一個類,繼承NCThread 類,調用start函數就可以啓動一個線程,線程調用子類的run函數
步驟:
- 定義父類NCThread,定義一個靜態函數,函數參數爲void*,這裏會傳該類的指針進來
- 父類NCThread中定義run函數,注意爲virtual,這樣纔可以調到子類的run函數
- 父類NCThread定義start函數,啓動一個線程,線程函數爲該類中的靜態函數,參數爲this指針
- 定義子類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;
}