您的位置:首页 > 编程语言

UNIX环境高级编程第11章线程

2015-02-06 21:30 302 查看
























程序清单11-1打印线程ID

//threads/threadid.c11-1 #include"apue.h" #include<pthread.h> pthread_tntid; voidprintids(constchar*s) { printf("%d",(unsignedint)ntid); printf("%ld",(unsignedlong)ntid); pid_tpid; pthread_ttid; pid=getpid(); tid=pthread_self(); //printf("%spid%utid%u(0x%x)\n",s,(unsignedint)pid,(unsignedint)tid,(unsignedint)tid); printf("%spid%lutid%lu(0x%lx)\n",s,(unsignedlong)pid,(unsignedlong)tid,(unsignedlong)tid); } void*thr_fn(void*arg) { printids("newthread:"); return((void*)0); } /*Thisexamplehastwooddities,whicharenecessarytohandleracesbetweenthemain *threadandthenewthread.(We'lllearnbetterwaystodealwiththeseconditionslater *inthischapter.)Thefirstistheneedtosleepinthemainthread.Ifitdoesn'tsleep,the *mainthreadmightexit,therebyterminatingtheentireprocessbeforethenewthread *getsachancetorun.Thisbehaviorisdependentontheoperatingsystem'sthreads *implementationandschedulingalgorithms. *ThesecondoddityisthatthenewthreadobtainsitsthreadIDbycalling *pthread_selfinsteadofreadingitoutofsharedmemoryorreceivingitasan *argumenttoitsthread-startroutine.Recallthatpthread_createwillreturnthe *threadIDofthenewlycreatedthreadthroughthefirstparameter(tidp).Inour *example,themainthreadstoresthisIDinntid,butthenewthreadcan¡¯tsafelyuseit. *Ifthenewthreadrunsbeforethemainthreadreturnsfromcallingpthread_create, *thenthenewthreadwillseetheuninitializedcontentsofntidinsteadofthethreadID. */ intmain(void) { interr; err=pthread_create(&ntid,NULL,thr_fn,NULL); if(0!=err) err_quit("can'tcreatethread:%s\n",strerror(err)); printids("mainthread:"); sleep(1); return0; }all:threadid
threadid:threadid.c
g++-g-Wallthreadid.c../lib/libapue.a-I../include-lpthread-othreadid
clean:
rmthreadid







这和我在虚拟机centos6.3中测试的情况不同,centos下进程ID是相同的(3607),并不是不同的。





内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: