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

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

原文地址: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选取的实现了
不同内核策略不同

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值