编写了一个多线程程序:
+PtgRjY1J:R
#include <unistd.h>
|m{({F#]4zB/X
#include <stdio.h>
ypP:i w su9BoG#include <pthread.h>
gF+X K6{7w/sqLinux伊甸园论坛
~}
`C4xj*V'o.?pthread_key_t key;
www.linuxeden.comf N a(N;j6@\*`$Gr
$K} R(MC,gLinux伊甸园论坛void echomsg(int t)
www.linuxeden.comhQ-TKvu!@5f
{
Linux伊甸园论坛_/k9]%N1E;n-r
printf("线程退出.\n");
G
TlfS(o7_.z9Rwww.linuxeden.com printf("destructor excuted in thread %d, param=%d\n",pthread_self(),t);
_$fy9jk!Z;EB*fQF
}
Linux伊甸园论坛b@8D+f$Mft@
oG:TV2Exk)S"__void *child1(void *arg) //为每一个线程单独建一个执行函数
4g2}6~%RMHS%axWI{
Linux伊甸园论坛i3K1{,z(rq`'i9P!c
int tid=pthread_self(); //求线程id号
zK1f&R:\1h\&h(ARLinux伊甸园论坛 printf("thread %d enter\n",tid);
!^ dy*x |&aTj pthread_setspecific(key,(void *)tid); //将tid的值与key相关联,注意不是*tid
!@5\,\dAp@8LU sleep(2);
www.linuxeden.com*A/p7q,|d3J+h
printf("thread %d returns %d \n", tid , pthread_getspecific(key)); //读出key值,即*tid?
w#uP6KzPND0]www.linuxeden.com sleep(5);
E
j fb
vn3Rm|5a"F$nwww.linuxeden.com F2@m:k#`0O
return NULL;
!Ej@ph x'g6@
C(XS$KvM\3Pl}
Linux伊甸园论坛X4v.KX:?-W#[
U7F2{)U
Y
$oE`J$ST1p(G9Nu*K.t
void *child2(void *arg)
Linux伊甸园论坛2}5{d+C5pQ
{
www.linuxeden.com#? Q&Ww
IY
int tid=pthread_self();
www.linuxeden.comV8bkN$yYUlbm
printf("thread %d enter\n",tid);
Linux伊甸园论坛5O*u0jR
S)\T M
pthread_setspecific(key,(void *)tid); //将tid的值与key相关联,注意不是*tid
O T E*M:hh:VTy+l
R$}
sleep(1);
/MT,BJO,\0Z6JE Hz printf("thread %d returns %d \n", tid , pthread_getspecific(key)); //读出key值,即*tid?
R2P6L'FX7c-~Linux伊甸园论坛 sleep(5);
gj^gn4?d4u b f;{ l.sE+[S1P)^4X
return NULL;
www.linuxeden.com
`A"i A"gOs
}
www.linuxeden.com V9t:mp5PC"h
!Sa
u)W)O!ky_&]h&a;_Y_'Pbp.h
int main()
5^\A X%Vz!gB9W
{
4DB&mc|
int tid1,tid2; //线程号
Wyt `b?P3x printf("hello\n");
t&G1o @
pthread_key_create(&key,echomsg); //注意在创建线程前创建私有数据,线程退出时会将key作为参数送入echomsg
z2|B|1pw)oc
pthread_create(&tid1,NULL,child1,NULL); //创建线程,其中第一个NULL是设置线程属性,第二个NULL是child1函数的传人参数.线程的作用就是执行child1.
W@t4QgkxP
pthread_create(&tid2,NULL,child2,NULL);
_&ht4Bq$Sxu sleep(10);
%Eey0t(f pthread_key_delete(key); //释放TSD
.j2kok9PEy-g printf("main thread exit\n");
2kh{2T N
5o)vw;H3\5ICV5^*K return 0;
/p6u/mbco/z6M
}
1iZ&eD
T:E
3x%G i
@Xq
编译时总提示
www.linuxeden.com3}v[5k xSkHY5c
/tmp/ccFXz8Ip.o(.text+0xde): In function `child2':
9}/mUfy)R
mythread.c: undefined reference to `pthread_setspecific'
? pVLl&S,T
/tmp/ccFXz8Ip.o(.text+0xfc):mythread.c: undefined reference to `pthread_getspecific'
j9M0r?D\ O
/tmp/ccFXz8Ip.o(.text+0x166): In function `main':
,d6|ee6?}:y3N
mythread.c: undefined reference to `pthread_key_create'
www.linuxeden.comP/H\'?'f"E%U/F:[
/tmp/ccFXz8Ip.o(.text+0x17b):mythread.c: undefined reference to `pthread_create'
TN|%H^%Z1C^(R
/tmp/ccFXz8Ip.o(.text+0x190):mythread.c: undefined reference to `pthread_create'
Ws7Kp_0X]
/tmp/ccFXz8Ip.o(.text+0x1ae):mythread.c: undefined reference to `pthread_key_delete'
ita)w.hZ