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,为什么就结束了啊,求大侠指教一下,谢谢!
[解决办法]
主程序退出,线程也就不存在了,呵呵
........
int x;
void* output( void* arg )
{
while(1) {
if (x > 20)
pthread_exit((void *)3);
//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;
void *tret[5];
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], &tret[i] ) )
{
fprintf( stderr, "failed to waite thread: %s\n ", strerror( errno ) );
return 1;
}
}
int j=0;
while(1)
{
for(i=0;i <5;i++)
if((int)tret[i] == 3) { printf( "thread %d exit \n ",i);j++ ;};
if(j == 5) break;
sleep(1);
}
return 0;
}
[解决办法]
1楼的已经说清楚了, 你的主程序,都退出了, 当然就不可能看到hello word 100了
想要看到,最简单的就多让主程序sleep吧