Linux下多线程问题,求大侠指教
问题如下:
有100个同样任务的队列,想用5个线程完成它
int x;
void* output( void* arg )
{
while(1) {
if (x >100) return NULL;
printf( "I am thread %d, Hello World! %d \n", pthread_self(),x++ );
sleep(3);
}
//return NULL;
}
int main( int argc, char** argv )
{
pthread_t tid[5] = { 0 };
int i = 0;
x=0;
for( i = 0; i < 5; i++ )
{
if( errno = pthread_create( tid + i, NULL, output, NULL ) )
{
fprintf( stderr, "failed to create thread: %s\n", strerror( errno ) );
return 1;
}
sleep(1); //时间设置不同结果运行不同
}
/*
for( i = 0; i < 5; i++ )
{
if( errno = pthread_join( tid[i], NULL ) )
{
fprintf( stderr, "failed to waite thread: %s\n", strerror( errno ) );
return 1;
}
}
*/
return 0;
}
编译运行结果如下:
I am thread 134558720, Hello World! 0
I am thread 134559232, Hello World! 1
I am thread 134558720, Hello World! 2
I am thread 134559744, Hello World! 3
I am thread 134559232, Hello World! 4
I am thread 134558720, Hello World! 5
I am thread 134560256, Hello World! 6
I am thread 134559744, Hello World! 7
I am thread 134559232, Hello World! 8
I am thread 134560768, Hello World! 9
I am thread 134558720, Hello World! 10
I am thread 134560256, Hello World! 11
I am thread 134559744, Hello World! 12
x还没到100,为什么就结束了啊,求大侠指教一下,谢谢!