十一月 15
在這個網站中看到這一段程式. 如下
mt.c (節錄自 Pthread Programming 一書)
----------------------------
#include
#include
#include
#include
#include
void do_one_thing(int *);
void do_another_thing(int *);
void do_wrap_up(int,int);
int r1=0, r2=0;
void main()
{
pthread_t thread1, thread2;
pthread_create(&thread1,NULL,(void*) do_one_thing, &r1);
pthread_create(&thread2,NULL,(void*) do_another_thing, &r2);
pthread_join(thread1,NULL);
pthread_join(thread2,NULL);
do_wrap_up(r1,r2);
}
void do_one_thing(int *i)
{
for( *i = 1; *i <= 100; (*i)++)
write(1,"do one thing.",13);
/*
如果用 printf() 或 outs() 這類使用緩衝區的函式,會受到
緩衝區的共用互斥影嚮,使得執行時顯示的訊息,不會出現交
叉出現的結果。
這也是 pthread 及 C Library 配合使用時,一個重要的效率
考量處:不當的使用 pthread ,反而會因系統呼叫的共用互斥
動作,折損了程式執行的效率,比使用單一thread的效率還差。
*/
}
void do_another_thing(int *i)
{
for( *i = 1; *i <= 100; (*i)++)
write(1,"[1;31mdo anther thing.[m",26);
}
void do_wrap_up(int i, int j)
{
printf("%d,%d:%d\n",i,j,i+j);
}
裡面那段中文註解, 讓我猶豫的狀態.....之前我的程式感覺效率很差, 是這個printf()造成的嗎??
仔細想想, 網路上的範例程式, 其printf() 都是放在pthread_mutex_lock() 之後耶....
改天來測測看
[11/19] 更新
程式很慢的原因, 終於找到問題了, 原來是2 個thread 一直用mutex 相互卡住造成的. 尤其是當某一thread 一直polling 某個被mutex 保護的變數時, 往往會造成另一thread 動作很慢. 解決方式是用condition 來讓polling 的thread 先睡覺去, 讓另一個thread 有時間做事, 等作完了, 再把睡覺的thread叫醒.