pthread_create的使用方法
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
pthread_create的使用方法.txt人生重要的不是所站的位置,而是所朝的方向。不要用自己的需求去衡量别人的给予,否则永远是抱怨。1:pthread_create 函数的安全使用问题
做过linux多线程开发的人都会用过pthread_create函数,但是很少人会注意到:主线程在使用pthread_create创建线程时,如果pthread_create 函数的第四个参数(指针参数)传入的值会被主线程随时修改时,这时我们的线程从pthread_create 函数的第四个参数获取的值可能就不是我们想要传入的值了。
看看下面代码:在 main 函数的 for 循环中创建10个线程;每创建一个线程时都把循环变量 i 的值通过 pthread_create 函数的第四个参数传入线程函数中;但是线程获取的值可能不并不是我们想传入的值。
#include
#include
void * threadFunc( void * pm_iPthreadId )
{
unsigned int iId = * ( unsigned int * ) pm_iPthreadId;
printf( "### No.%d pthread start exec; pthread id = %u !\n", iId, pthread_self() );
time_t iStartTime = time( NULL );
while(1)
{
time_t iTempTime = time( NULL );
if ( iTempTime - iStartTime > 2 )
{
printf( "$$$ NO.%d pthread cirle exec !\n", * ( unsigned int * ) pm_iPthreadId );
iStartTime = time( NULL );
}
}
}
int main()
{
pthread_t * pthreadId;
pthreadId = new pthread_t[10];
for( unsigned int i = 0; i < 10; i++ )
{
int iRet = pthread_create( pthreadId + i, NULL, threadFunc, &i ); if ( iRet == 0 )
{
printf( "@@@ create No.%d pthread success; pthreadId = %u !\n", i, pthreadId + i );
}
}
while(1)
{
}
return 0;
}
程序运行结果如下(结果是随机的,每次运行可能都不一样):
@@@ create No.0 pthread success; pthreadId = 138174472 ! ### No.1 pthread start exec; pthread id = 3076803472 ! ### No.1 pthread start exec; pthread id = 3087293328 ! @@@ create No.1 pthread success; pthreadId = 138174476 ! @@@ create No.2 pthread success; pthreadId = 138174480 ! ### No.3 pthread start exec; pthread id = 3055823760 ! ### No.3 pthread start exec; pthread id = 3066313616 ! @@@ create No.3 pthread success; pthreadId = 138174484 ! ### No.4 pthread start exec; pthread id = 3045333904 ! @@@ create No.4 pthread success; pthreadId = 138174488 ! @@@ create No.5 pthread success; pthreadId = 138174492 ! ### No.6 pthread start exec; pthread id = 3024354192 ! ### No.6 pthread start exec; pthread id = 3034844048 ! @@@ create No.6 pthread success; pthreadId = 138174496 ! @@@ create No.7 pthread success; pthreadId = 138174500 ! ### No.8 pthread start exec; pthread id = 3003374480 ! ### No.8 pthread start exec; pthread id = 3013864336 ! @@@ create No.8 pthread success; pthreadId = 138174504 ! @@@ create No.9 pthread success; pthreadId = 138174508 ! ### No.10 pthread start exec; pthread id = 2992884624 ! $$$ NO.10 pthread cirle exec !
$$$ NO.10 pthread cirle exec !
$$$ NO.10 pthread cirle exec !
$$$ NO.10 pthread cirle exec !
$$$ NO.10 pthread cirle exec !
$$$ NO.10 pthread cirle exec !
$$$ NO.10 pthread cirle exec !
$$$ NO.10 pthread cirle exec !
$$$ NO.10 pthread cirle exec !
$$$ NO.10 pthread cirle exec !
$$$ NO.10 pthread cirle exec !
$$$ NO.10 pthread cirle exec !
$$$ NO.10 pthread cirle exec !
$$$ NO.10 pthread cirle exec !