- 論壇徽章:
- 0
|
#1 可重入:
在apue第二版 10.6 可重入函數(shù)中,講到malloc函數(shù)是不可重入的
那么我在以下多線程中:
- thread1()
- {
- malloc(...)
- ...
- free(..)
- }
- thread2()
- {
- malloc(...)
- ...
- free(..)
- }
復(fù)制代碼
這樣會(huì)不會(huì)可能導(dǎo)致進(jìn)程崩潰呢?(我一直都是這樣寫的 ,難道我一直都是錯(cuò)的么??)
#2 原子操作:
我想對(duì)一全局量進(jìn)行+ ,-操作,windows下有Interlocked函數(shù)族 ,通過對(duì)內(nèi)存總線加鎖,
來實(shí)現(xiàn)相應(yīng)操作,x86匯編指令貌似是 asm:lock之類的,故此函數(shù)族非常高效,僅需幾個(gè)指令
周期,unix/linux 下有沒有通用的、高效的方法呢?(mutex加鎖太耗費(fèi)料,實(shí)在不想用這個(gè))
我嘗試寫了以下函數(shù):
- void atomic_inc(int *p)
- {
- volatile static int flag=0;
- while(flag);
- flag = 1;
- *p = *p + 1;
- flag = 0;
- }
復(fù)制代碼
gcc -S -O3編譯,查看匯編指令發(fā)現(xiàn)此方法行不通:
- .L3:
- movl flag.1280, %eax
- testl %eax, %eax
- jne .L3
- movl $1, flag.1280
- addl $1, (%edx)
- popl %ebp
- movl $0, flag.1280
- ret
- )
復(fù)制代碼
#3 線程安全:
apue 12.5列出了一坨"不能"保證線程安全的函數(shù),比如rand,ctime ,lcoaltime,
inet_ntoa,gethostbyname等,在windows下,crt線程函數(shù)_beginthread 在調(diào)用系統(tǒng)api
createthread 之前,會(huì)創(chuàng)建一個(gè)結(jié)構(gòu)體_tiddata,來存放這類函數(shù)的靜態(tài)數(shù)據(jù)以及errno等,
大家平時(shí)在unix下多線程編程是如何搞定這些函數(shù)的?還是干脆視而不見呢?
#4 關(guān)于這方面有沒有什么權(quán)威的資料呢,各位推薦下和呵!
[ 本帖最后由 windyrobin 于 2009-3-27 10:51 編輯 ] |
|