在C++的类中封装多线程
生活随笔
收集整理的這篇文章主要介紹了
在C++的类中封装多线程
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
在C++的類中,普通成員函數(shù)不能作為pthread_create的線程函數(shù),如果要作為pthread_create中的線程函數(shù),必須是static
? ? ? ? ??在C++的類中,普通成員函數(shù)不能作為pthread_create的線程函數(shù),如果要作為pthread_create中的線程函數(shù),必須是static !
??????? 在C語(yǔ)言中,我們使用pthread_create創(chuàng)建線程,線程函數(shù)是一個(gè)全局函數(shù),所以在C++中,創(chuàng)建線程時(shí),也應(yīng)該使用一個(gè)全局函數(shù)。static定義的類的成員函數(shù)就是一個(gè)全局函數(shù)。
?
更多 參考 ?http://blog.csdn.net/ksn13/article/details/40538083?
?
?
#include <pthread.h> #include <unistd.h> #include <stdio.h> #include <stdlib.h>class Thread {private:pthread_t pid;private:static void * start_thread(void *arg);//?//靜態(tài)成員函數(shù)public: int start();virtual void run() = 0; //基類中的虛函數(shù)要么實(shí)現(xiàn),要么是純虛函數(shù)(絕對(duì)不允許聲明不實(shí)現(xiàn),也不純虛) };int Thread::start() {if(pthread_create(&pid,NULL,start_thread,(void *)this) != 0) //′創(chuàng)建一個(gè)線程(必須是全局函數(shù)){ return -1; } return 0; }void* Thread::start_thread(void *arg) //靜態(tài)成員函數(shù)只能訪問(wèn)靜態(tài)變量或靜態(tài)函數(shù),通過(guò)傳遞this指針進(jìn)行調(diào)用 {Thread *ptr = (Thread *)arg;ptr->run(); //線程的實(shí)體是run }class MyThread:public Thread {public: void run(); }; void MyThread::run() {printf("hello world\n"); }int main(int argc,char *argv[]) {MyThread myThread;myThread.start();//test.run();sleep(1);return 0; }編譯運(yùn)行:
diego@ubuntu:~/myProg/pthreadCpp$ g++ main.cpp -lpthread diego@ubuntu:~/myProg/pthreadCpp$ ./a.out hello world diego@ubuntu:~/myProg/pthreadCpp$?
《新程序員》:云原生和全面數(shù)字化實(shí)踐50位技術(shù)專家共同創(chuàng)作,文字、視頻、音頻交互閱讀總結(jié)
以上是生活随笔為你收集整理的在C++的类中封装多线程的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: C++之全局函数和成员函数互相转换
- 下一篇: MQTT protocol level的