以下是我的程式:
#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 );
}
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是負的?/
如何解決呢??
【lw1a2】:
程式沒問題,我這裡是正數
【ccdd14】:
我又運作了一遍, 結果還是負數!!
為什麼輸出的是負數呢?
難道是編譯器的問題嗎?
【jufeng2309】:
pthread_create( &(tid + i), NULL, output, NULL )
【smilefox】:
printf( "I am thread %d, Hello World!\n", pthread_self() );
%d 改為 %lu 即可
【p_zyh】:
lz正解
打出來是負數說明超出了int的最大值
如果你是想問為什麼線程id會如此大的話
就要看核心對線程id選取的實作了
不同核心政策不同