[問題] 把 fread 獨立出來後 變超慢
有問題想問版上大大們
最近在linux下寫一個程式
主要是把 讀檔(讀gzip)的部分 全交給一個thread 來做
然後其他threads 負責處理讀進來的字元
有測試只跑 fileRead,不跑 getData,速度是正常的
但若一個thread 跑fileRead,四個threads getData 執行速度卻變得超級超級慢
目前還不知變慢的確切原因,
有懷疑是lock unlock 在context switch overhead 太高
所以想請板上大大提供些意見,還是說這樣的 implement 不可行?
程式碼大概如下:
int isEof = 0;
string str;
void fileRead(FILE *fp){
isEof = 0
char buf[1025];
while (!isEof){
int result = Fread(buf, 1, 1024, fp);
if (result == 0) { isEof = 1;}
pthread_mutex_lock(&lock);
str.append(buf);
pthread_mutex_unlock(&lock);
}}
int getData(char buf[1025], int sz = 1024){
while (!isEof && str.size() < sz) {
}
int sz = str.size() >= sz ? sz : str.size();
pthread_mutex_lock(&lock);
str.copy(buf, sz, 0);
str.erase(0, sz);
pthread_mutex_unlock(&lock);
return sz;
}
PS:
附上io循序版本的getData
getData(char buf[1025], int sz = 1024){
return Fread(buf, 1, sz, fp)
}
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 114.43.178.244
→
08/22 00:34, , 1F
08/22 00:34, 1F
→
08/22 00:36, , 2F
08/22 00:36, 2F
→
08/22 00:38, , 3F
08/22 00:38, 3F
→
08/22 00:42, , 4F
08/22 00:42, 4F
→
08/22 00:48, , 5F
08/22 00:48, 5F
→
08/22 00:50, , 6F
08/22 00:50, 6F
推
08/22 01:56, , 7F
08/22 01:56, 7F
→
08/22 03:54, , 8F
08/22 03:54, 8F
→
08/22 03:55, , 9F
08/22 03:55, 9F
→
08/22 03:57, , 10F
08/22 03:57, 10F
→
08/22 03:57, , 11F
08/22 03:57, 11F
→
08/22 07:56, , 12F
08/22 07:56, 12F
→
08/22 08:02, , 13F
08/22 08:02, 13F
→
08/22 08:07, , 14F
08/22 08:07, 14F
→
08/22 08:08, , 15F
08/22 08:08, 15F
→
08/22 08:14, , 16F
08/22 08:14, 16F
※ 編輯: mantix 來自: 114.43.176.234 (08/22 08:16)
※ 編輯: mantix 來自: 114.43.176.234 (08/22 08:17)
→
08/22 08:18, , 17F
08/22 08:18, 17F
※ 編輯: mantix 來自: 114.43.176.234 (08/22 08:20)
→
08/22 08:22, , 18F
08/22 08:22, 18F
※ 編輯: mantix 來自: 114.43.176.234 (08/22 08:26)
→
08/22 08:27, , 19F
08/22 08:27, 19F
→
08/24 13:41, , 20F
08/24 13:41, 20F
→
08/24 13:41, , 21F
08/24 13:41, 21F
→
08/24 13:43, , 22F
08/24 13:43, 22F
C_and_CPP 近期熱門文章
PTT數位生活區 即時熱門文章