《Unix环境高级编程》:打印线程ID

《Unix环境高级编程》这本书附带了许多短小精美的小程序,我在阅读此书的时候,将书上的代码按照自己的理解重写了一遍(大部分是抄书上的),加深一下自己的理解(纯看书太困了,呵呵)。此例子在Ubuntu10.04上测试通过。


程序简介:以下这个程序创建一个线程并且打印进程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;
}


运行示例(红色字体的为输入):

qch@ubuntu:~/code$gcc temp.c -lpthread -o temp 
qch@ubuntu:~/code$ ./temp
main thread:  pid 4153 tid 3078440640 (0xb77d46c0)
new thread:  pid 4153 tid 3078437744 (0xb77d3b70)

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值