linux 下的线程问题, 请帮帮忙!!
以下是我的程序:
#include <stdio.h>
#include <pthread.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/stat.h>
void* output( void* arg )
{
printf( "I am thread %d, Hello World!\n ", pthread_self() );
return NULL;
}
int main( int argc, char** argv )
{
pthread_t tid[5] = { 0 };
int i = 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 -151069776, Hello World!
I am thread -161563728, Hello World!
I am thread -172053584, Hello World!
I am thread -182543440, Hello World!
I am thread -193033296, Hello World!
为什么线程ID是负的?/
如何解决呢??
[解决办法]
程序没问题,我这里是正数
[解决办法]
printf( "I am thread %d, Hello World!\n ", pthread_self() );
%d 改为 %lu 即可
[解决办法]
lz正解
打出来是负数说明超出了int的最大值
如果你是想问为什么线程id会如此大的话
就要看内核对线程id选取的实现了
不同内核策略不同