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

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

muduo学习笔记 线程类

發布時間:2024/4/18 编程问答 27 豆豆
生活随笔 收集整理的這篇文章主要介紹了 muduo学习笔记 线程类 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

learn_muduo

線程屬性

  • 線程標識 pthreadId_,pid_t
  • 線程函數 func_
  • 線程名字 name_
  • 線程序號 numCreated_
bool started_; // 線程狀態標識 bool joined_; pthread_t pthreadId_; // pthread_函數使用 pid_t tid_; // 線程標識 ThreadFunc func_; // 線程函數 string name_; // 線程名字 CountDownLatch latch_; // 倒計時 static AtomicInt32 numCreated_; // 線程序號

pthread_t的值很大,無法作為一些容器的key值。 glibc的Pthreads實現實際上把pthread_t作為一個結構體指針,指向一塊動態分配的內存,但是這塊內存是可以反復使用的,也就是說很容易造成pthread_t的重復。也就是說pthreads只能保證同一進程內,同一時刻的各個線程不同;不能保證同一個進程全程時段每個線程具有不同的id,不能保證線程id的唯一性。

在LINUX系統中,建議使用gettid()系統調用的返回值作為線程id,這么做的原因:
返回值是一個pid_t,其值是一個很小的整數,方便輸出。
在linux系統中,它直接標識內核任務調度id,可通過/proc文件系統中找到對應項:/proc/tid 或者 /proc/pid/task/tid,方便定位到具體線程。任何時刻都是唯一的,并且由于linux分配新的pid采用遞增輪回辦法,短時間內啟動多個線程也會具有不同的id。

執行過程

new Thread

通過new Thread(&threadFunc)初始化創建Thread

Thread::Thread(ThreadFunc func, const string& n): started_(false),joined_(false),pthreadId_(0),tid_(0),func_(std::move(func)),name_(n),latch_(1) {setDefaultName(); }

在Thread的構造函數中,初始化線程屬性。同時調用setDefaultName()設置線程的名字name_

void Thread::setDefaultName() {int num = numCreated_.incrementAndGet();if (name_.empty()) {char buf[32];snprintf(buf, sizeof buf, "Thread%d", num);name_ = buf;} }

start

void Thread::start() {assert(!started_);started_ = true;detail::ThreadData* data = new detail::ThreadData(func_, name_, &tid_, &latch_);if (pthread_create(&pthreadId_, NULL, &detail::startThread, data)){started_ = false;delete data;// LOG_SYSFATAL << "Failed in pthread_create";} else {latch_.wait();assert(tid_ > 0);} }

start()在堆上創建ThreadData對象,作為線程函數的參數,然后通過pthread_create()創建并啟動線程。

ThreadData包含了線程的基本屬性.

typedef muduo::Thread::ThreadFunc ThreadFunc; ThreadFunc func_; string name_; pid_t* tid_; CountDownLatch* latch_;ThreadData(ThreadFunc func,const string& name,pid_t* tid,CountDownLatch* latch): func_(std::move(func)),name_(name),tid_(tid),latch_(latch){}

當pthread_creat()創建成功,接著是倒計時類latch_.wait(),初始的 count_ = 1,主線程阻塞到mutex_上等待線程的結束。

void CountDownLatch::wait() {MutexLockGuard lock(mutex_);while (count_ > 0) {condition_.wait();} } void wait() {MutexLock::UnassignGuard ug(mutex_);int ret = pthread_cond_wait(&pcond_, mutex_.getPthreadMutex()); // 將線程添加到條件變量assert(ret == 0); }

runInThread

線程函數的執行是通過ThreadData中的runInThread調用func_()完成的。

void runInThread() {*tid_ = muduo::CurrentThread::tid();tid_ = NULL;latch_->countDown(); // 倒計時減1latch_ = NULL;muduo::CurrentThread::t_threadName = name_.empty() ? "muduoThread" : name_.c_str();::prctl(PR_SET_NAME, muduo::CurrentThread::t_threadName);try{func_(); // 執行線程函數muduo::CurrentThread::t_threadName = "finished";} catch (const Exception& ex) {muduo::CurrentThread::t_threadName = "crashed";fprintf(stderr, "exception caught in Thread %s\n", name_.c_str());fprintf(stderr, "reason: %s\n", ex.what());fprintf(stderr, "stack trace: %s\n", ex.stackTrace());abort();} catch (const std::exception& ex) {muduo::CurrentThread::t_threadName = "crashed";fprintf(stderr, "exception caught in Thread %s\n", name_.c_str());fprintf(stderr, "reason: %s\n", ex.what());} catch (...) {muduo::CurrentThread::t_threadName = "crashed";fprintf(stderr, "unknow exception caught in Thread %s\n", name_.c_str());throw;} }

當子線程開始執行,倒計時的latch_.count_ == 0,就會調用condition.notrifyAll()喚醒阻塞的主線程。

void notifyAll() {int ret = pthread_cond_broadcast(&pcond_);assert(ret == 0); }

測試程序

依次使用1到8個線程,每個線程向vector中push1千萬個數,測試他們需要的時間

#include "muduo/base/Timestamp.h" #include "muduo/base/Mutex.h" #include "muduo/base/Thread.h" #include "muduo/base/CountDownLatch.h"#include <iostream> #include <stdio.h> #include <boost/bind.hpp> #include <boost/ptr_container/ptr_vector.hpp> #include <vector>muduo::MutexLock g_mutex; // 聲明鎖 std::vector<int> g_vec; const int kCount = 10000000; // 每次插入1000w個數void threadFunc() {for (int i = 0; i < kCount; ++i) {muduo::MutexLockGuard lock(g_mutex); // 上鎖g_vec.push_back(i);} }void test_Mutex() {std::cout << "---- Mutex ----\n";const int kMaxThreads = 8; // 最多8個線程g_vec.reserve(kMaxThreads * kCount); // 提前分配大小muduo::Timestamp start(muduo::Timestamp::now()); // 當前時間戳// 單個線程不用鎖的時間for (int i = 0; i < kCount; ++i) {g_vec.push_back(i);}printf("1 thread(s) without lock %f\n", muduo::timeDifference(muduo::Timestamp::now(), start));for (int i = 0; i < kMaxThreads; ++i) {// i個線程用鎖的時間boost::ptr_vector<muduo::Thread> threads;g_vec.clear();start = muduo::Timestamp::now(); // 更新時間戳for (int j = 0; j <= i; ++j) {threads.push_back(new muduo::Thread(&threadFunc)); // 創建線程threads.back().start(); // 啟動線程 }for (int j = 0; j <= i; ++j) {threads[j].join(); // 回收線程}printf("%d thread(s) without lock %f\n", i+1, muduo::timeDifference(muduo::Timestamp::now(), start));} }int main() {test_Mutex();return 0; }/* ---- Mutex ---- 1 thread(s) without lock 0.390272 1 thread(s) with lock 1.485214 2 thread(s) with lock 10.677879 3 thread(s) with lock 11.748183 4 thread(s) with lock 16.022083 5 thread(s) with lock 19.676071 6 thread(s) with lock 23.740399 7 thread(s) with lock 27.879850 8 thread(s) with lock 32.507374 */

總結

以上是生活随笔為你收集整理的muduo学习笔记 线程类的全部內容,希望文章能夠幫你解決所遇到的問題。

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