日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > c/c++ >内容正文

c/c++

C++学习之路: 线程封装(基于对象编程)

發布時間:2023/12/4 c/c++ 24 豆豆
生活随笔 收集整理的這篇文章主要介紹了 C++学习之路: 线程封装(基于对象编程) 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

引言:

此次我們重新封裝線程, 采用基于對象編程的方式,不用于面向對象編程中重定義虛函數的方式,這里我們用回調函數的方式。

Thread.h

1 #ifndef THREAD_H_ 2 #define THREAD_H_ 3 4 #include <boost/noncopyable.hpp> 5 #include <functional> 6 #include <pthread.h> 7 8 class Thread : boost::noncopyable 9 { 10 public: 11 typedef std::function<void ()> ThreadCallback; 12 13 Thread(ThreadCallback callback); 14 ~Thread(); 15 16 void start(); 17 void join(); 18 19 static void *runInThread(void *); 20 21 private: 22 pthread_t threadId_; 23 bool isRunning_; 24 ThreadCallback callback_; //回調函數 25 }; 26 27 28 29 #endif //THREAD_H_

?

可以看到沒有重定義虛函數, 而是設置了一個函數適配器, 用于保存我們想要的業務邏輯。

直接用 靜態函數 runInThread 調用 callback_即可。

?

Thread.cpp

1 #include "Thread.h" 2 3 Thread::Thread(ThreadCallback callback) 4 : threadId_(0), 5 isRunning_(false), 6 callback_(std::move(callback)) 7 { 8 9 } 10 11 Thread::~Thread() 12 { 13 if(isRunning_) 14 { 15 //detach 16 pthread_detach(threadId_); 17 } 18 } 19 20 void Thread::start() 21 { 22 pthread_create(&threadId_, NULL, runInThread, this); 23 isRunning_ = true; 24 } 25 void Thread::join() 26 { 27 pthread_join(threadId_, NULL); 28 isRunning_ = false; 29 } 30 31 void *Thread::runInThread(void *arg) 32 { 33 Thread *pt = static_cast<Thread*>(arg); 34 pt->callback_(); //調用回調函數 35 36 return NULL; 37 }

以上 有幾點經驗處理, Google推薦 當Thread 這個類析構時,如果線程還沒有執行完, 那么就detach。

并設置一個標志位 bool isRunning 標志線程是否啟動。

?

測試代碼

1 #include "Thread.h" 2 #include <stdio.h> 3 #include <unistd.h> 4 using namespace std; 5 6 void foo() 7 { 8 while(1) 9 { 10 printf("foo\n"); 11 sleep(1); 12 } 13 } 14 15 16 17 int main(int argc, char const *argv[]) 18 { 19 Thread t(&foo); 20 21 t.start(); 22 t.join(); 23 24 return 0; 25 }

可以看到, 當用基于對象編程時, 不需要在定義用戶自己的類了, 只需在主函數傳入一個函數適配器即可。 具體函數類型可以用bind來實現。

?

測試代碼2

1 #include "Thread.h" 2 #include <stdio.h> 3 #include <unistd.h> 4 using namespace std; 5 6 class Foo 7 { 8 public: 9 void foo(int i) 10 { 11 while(1) 12 { 13 printf("foo %d\n", i++); 14 sleep(1); 15 } 16 } 17 }; 18 19 20 21 int main(int argc, char const *argv[]) 22 { 23 Foo f; 24 int i = 34; 25 Thread t(bind(&Foo::foo, &f, i)); 26 27 t.start(); 28 t.join(); 29 30 return 0; 31 }

?

對于 類的成員函數 同理使用 大殺器bind

?

轉載于:https://www.cnblogs.com/DLzhang/p/4023369.html

總結

以上是生活随笔為你收集整理的C++学习之路: 线程封装(基于对象编程)的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。