linux下的c 多執行緒封裝

2021-07-27 19:57:40 字數 1852 閱讀 5356

最近為了學習linux 下的多執行緒,自己用c++封裝了乙個簡易的區域網多執行緒聊天伺服器,期間遇到了一些坑寫到這裡與大家共勉!

主要功能: 封裝了乙個名叫pthread_serv的類對每乙個客戶端的響應建立乙個程序進行資訊**。

遇到的問題:在使用linux提供的執行緒建立函式

int pthread_create(pthread_t *tidp,const pthread_attr_t *attr,

(void*)(*start_rtn)(void*),void *arg)

時因為執行緒主函式start_rt函式是pthread_serv類中的普通函式,在呼叫的時候c++ 會隱式的傳入this指標,這樣start_rtn就有了兩個引數,但linux提供的pthread_create函式中start_rtn只能有乙個(void*) 引數,這是個很嚴重的問題,我們編譯都過不去…..

針對該問題的解決方法: 很明顯,我們必須乾掉start_rtn中這個可惡的this指標。現在有兩個辦法可以做到這點:

1. 將start_rtn宣告為該類的友元函式

2. 將start_rtn宣告為靜態函式

我用了第二種方法,將start_rtn宣告為靜態函式,這樣再呼叫

int pthread_create(pthread_t *tidp,const pthread_attr_t *attr,

(void*)(*start_rtn)(void*),void *arg)

就沒有問題了,不過舊問題去了,新問題又來了!!! 想哭…。c++ 中靜態函式中只能呼叫靜態成員,靜態函式。所以start_rtn函式不能呼叫類裡面的變數&&函式了,我也不能將所有的變數,函式都宣告成靜態的吧。所以我的解決方法是將this指標當做start_rtn的引數。

pthread_create(&id_t,null,hander_clnt,this);
再在start_rtn中將引數型別轉化成乙個物件指標,用這個物件指標呼叫乙個普通的函式,這個普通的函式就作為執行緒主函式使用。

void* pthread_serv::hander_clnt(void *msg)

下面是我的**,比較搓,求輕拍..(逃~~)

#ifndef pthread_serv_h

#define pthread_serv_h

#include

#include

#include

#include

#include

#include //sockaddr_in

#include

#include

#include

class pthread_serv

;#endif // pthread_serv_h

#include "pthread_serv.h"

pthread_serv::pthread_serv()

inline

void pthread_serv::error_hander(char *msg)

void pthread_serv::send_msg(char *msg,int len)

void pthread_serv::run_clnt()

void* pthread_serv::hander_clnt(void *msg)

void pthread_serv::run()

}

多執行緒封裝

每個成員函式 除了在第 12.6 節介紹的 static 成員函式外 都有乙個額外的 隱含的形參 this。為了理解成員函式的呼叫,可考慮下面的語句 total.same isbn trans 就如編譯器這樣重寫這個函式呼叫,this指標被傳入成員函式 sales item same isbn to...

Linux下多執行緒的執行緒保護

目錄 一 開發環境 二 互斥鎖 系統 ubuntu16.04 執行緒庫 pthread 語言 c c linux下的執行緒保護,最常用的是互斥鎖 條件變數 訊號量和讀寫鎖。先來試一下互斥鎖吧 多執行緒之間可能需要互斥的訪問一些全域性變數,這就需要互斥的來訪問,這些需要共享訪問的字段被稱作是臨界資源,...

linux下c語言的多執行緒程式設計

們在寫linux的服務的時候,經常會用到linux的多執行緒技術以提高程式效能 多執行緒的一些小知識 乙個應用程式可以啟動若干個執行緒。執行緒 lightweight process,lwp 是程式執行的最小單元。一般乙個最簡單的程式最少會有乙個執行緒,就是程式本身,也就是主函式 單執行緒的程序可以...