2011-03-23 63 views
0

我仔细检查了我在维护的某些代码中所做的一些假设。main()的pthread ID默认为0吗?

我正确理解程序的main()的pthread ID总是被定义为0吗?

因此,举例来说:

#include <pthread.h> 
#include <cstdio> 

int main(){ 
    printf("Main ID is %X\n", (unsigned int)pthread_self()); 
} 

将始终打印0?

这似乎是它在我自己的系统上的工作原理(Linux,GNU_LIBPTHREAD_VERSION是:NPTL 2.11.1),但是我还没有设法在对pthread库的各种解释中找到对此定义的任何引用。我想知道这种行为是否可靠和便携,还是只是本地侥幸。谢谢!

回答

4

pthread_t应视为不透明类型;有一个函数pthread_equal(),您应该使用它来比较线程pthread_t对象。强制转换为unsigned int肯定是未定义的行为,与使用==比较int。

+0

...好点。很高兴我在检查。 – Ziv 2011-03-23 12:26:52

1

一位名叫“失业的俄罗斯人”的人编辑了我的其他答案,包括以下内容;我个人不会购买它,但也许有一些东西呢?

此外,你得到的零仅仅是因为你根本没有连接libpthread。试想一下:

#include <pthread.h> 
#include <cstdio> 

int main(){ 
    printf("Main ID is %lx\n", (unsigned long)pthread_self()); 
} 

$ g++ -g t.c && ./a.out 
Main ID is 0 
$ g++ -g t.c -pthread && ./a.out 
Main ID is 7fd1a288d720 

我不买这个,因为我的MacBook,我得到

$ g++ -g t.c && ./a.out 
Main ID is a092e720 
+1

这是特定于实现的。当然,有一些(IMO破坏的)实现,其中真正的'pthread_self'在'libpthread'中,而存根pthread函数存在于主libc中,所以如果发生这种情况我一点都不感到惊讶。另一方面,它绝对不是你可以依赖的东西。 – 2011-05-21 15:04:43