多线程id为什么是负的?原因

来源:互联网 发布:js onclickbutton 编辑:程序博客网 时间:2024/04/27 17:20

/******************************************************************************************************************

原文地址:http://www.programfan.com/CLUB/showpost.asp?id=985

说明:为什么线程ID是负的?

******************************************************************************************************************/ 

以下是我的程序:


#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是负的?/
如何解决呢??


【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选取的实现了
不同内核策略不同

0 0
原创粉丝点击