《APUE》:打印线程ID
《APUE》:打印线程ID
《Unix环境高级编程》这本书附带了许多短小精美的小程序,我在阅读此书的时候,将书上的代码按照自己的理解重写了一遍(大部分是抄书上的),加深一下自己的理解(纯看书太困了,呵呵)。此例子在Ubuntu 10.04上测试通过。
相关链接
- 《UNIX环境高级编程》(第二版)apue.h的错误
- Unix环境高级编程 源代码地址
程序简介:以下这个程序创建一个线程并且打印进程ID,新线程的ID以及初始线程的线程的ID
- //《APUE》程序11-1:创建一个子线程并打印其线程ID
- #include <unistd.h>
- #include <stdio.h>
- #include <stdlib.h>
- #include <pthread.h>
- pthread_t ntid;
- void printfids(const char *s)
- {
- //打印当前线程的进程ID和线程ID
- pid_t pid = getpid();
- pthread_t tid = pthread_self();
- printf("%s pid %u tid %u (0x%x)\n",s, (unsigned int)pid,
- (unsigned int)tid, (unsigned int)tid);
- }
- void *thr_fn(void *arg)
- {
- printfids("new thread: ");
- return (void*)0;
- }
- int main(void)
- {
- pthread_create(&ntid, NULL, thr_fn, NULL);
- printfids("main thread: ");
- //让主线程睡眠1秒钟,这是保证子线程可以运行的一种权宜之计
- sleep(1);
- return 0;
- }
运行示例(红色字体的为输入):
www.bkjia.com @ubuntu:~/code$ gcc temp.c -lpthread -o temp
www.bkjia.com @ubuntu:~/code$ ./temp
main thread: pid 4153 tid 3078440640 (0xb77d46c0)
new thread: pid 4153 tid 3078437744 (0xb77d3b70)
评论暂时关闭