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

歡迎訪(fǎng)問(wèn) 生活随笔!

生活随笔

當(dāng)前位置: 首頁(yè) > 编程资源 > 编程问答 >内容正文

编程问答

muduo学习笔记 线程类

發(fā)布時(shí)間:2024/4/18 编程问答 31 豆豆
生活随笔 收集整理的這篇文章主要介紹了 muduo学习笔记 线程类 小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

learn_muduo

線(xiàn)程屬性

  • 線(xiàn)程標(biāo)識(shí) pthreadId_,pid_t
  • 線(xiàn)程函數(shù) func_
  • 線(xiàn)程名字 name_
  • 線(xiàn)程序號(hào) numCreated_
bool started_; // 線(xiàn)程狀態(tài)標(biāo)識(shí) bool joined_; pthread_t pthreadId_; // pthread_函數(shù)使用 pid_t tid_; // 線(xiàn)程標(biāo)識(shí) ThreadFunc func_; // 線(xiàn)程函數(shù) string name_; // 線(xiàn)程名字 CountDownLatch latch_; // 倒計(jì)時(shí) static AtomicInt32 numCreated_; // 線(xiàn)程序號(hào)

pthread_t的值很大,無(wú)法作為一些容器的key值。 glibc的Pthreads實(shí)現(xiàn)實(shí)際上把pthread_t作為一個(gè)結(jié)構(gòu)體指針,指向一塊動(dòng)態(tài)分配的內(nèi)存,但是這塊內(nèi)存是可以反復(fù)使用的,也就是說(shuō)很容易造成pthread_t的重復(fù)。也就是說(shuō)pthreads只能保證同一進(jìn)程內(nèi),同一時(shí)刻的各個(gè)線(xiàn)程不同;不能保證同一個(gè)進(jìn)程全程時(shí)段每個(gè)線(xiàn)程具有不同的id,不能保證線(xiàn)程id的唯一性。

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

執(zhí)行過(guò)程

new Thread

通過(guò)new Thread(&threadFunc)初始化創(chuàng)建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的構(gòu)造函數(shù)中,初始化線(xiàn)程屬性。同時(shí)調(diào)用setDefaultName()設(shè)置線(xiàn)程的名字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()在堆上創(chuàng)建ThreadData對(duì)象,作為線(xiàn)程函數(shù)的參數(shù),然后通過(guò)pthread_create()創(chuàng)建并啟動(dòng)線(xiàn)程。

ThreadData包含了線(xiàn)程的基本屬性.

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){}

當(dāng)pthread_creat()創(chuàng)建成功,接著是倒計(jì)時(shí)類(lèi)latch_.wait(),初始的 count_ = 1,主線(xiàn)程阻塞到mutex_上等待線(xiàn)程的結(jié)束。

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()); // 將線(xiàn)程添加到條件變量assert(ret == 0); }

runInThread

線(xiàn)程函數(shù)的執(zhí)行是通過(guò)ThreadData中的runInThread調(diào)用func_()完成的。

void runInThread() {*tid_ = muduo::CurrentThread::tid();tid_ = NULL;latch_->countDown(); // 倒計(jì)時(shí)減1latch_ = NULL;muduo::CurrentThread::t_threadName = name_.empty() ? "muduoThread" : name_.c_str();::prctl(PR_SET_NAME, muduo::CurrentThread::t_threadName);try{func_(); // 執(zhí)行線(xiàn)程函數(shù)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;} }

當(dāng)子線(xiàn)程開(kāi)始執(zhí)行,倒計(jì)時(shí)的latch_.count_ == 0,就會(huì)調(diào)用condition.notrifyAll()喚醒阻塞的主線(xiàn)程。

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

測(cè)試程序

依次使用1到8個(gè)線(xiàn)程,每個(gè)線(xiàn)程向vector中push1千萬(wàn)個(gè)數(shù),測(cè)試他們需要的時(shí)間

#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個(gè)數(shù)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è)線(xiàn)程g_vec.reserve(kMaxThreads * kCount); // 提前分配大小muduo::Timestamp start(muduo::Timestamp::now()); // 當(dāng)前時(shí)間戳// 單個(gè)線(xiàn)程不用鎖的時(shí)間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個(gè)線(xiàn)程用鎖的時(shí)間boost::ptr_vector<muduo::Thread> threads;g_vec.clear();start = muduo::Timestamp::now(); // 更新時(shí)間戳for (int j = 0; j <= i; ++j) {threads.push_back(new muduo::Thread(&threadFunc)); // 創(chuàng)建線(xiàn)程threads.back().start(); // 啟動(dòng)線(xiàn)程 }for (int j = 0; j <= i; ++j) {threads[j].join(); // 回收線(xiàn)程}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 */

總結(jié)

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

如果覺(jué)得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。