UNIX环境高级编程第11章线程
程序清单11-1打印线程ID
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 | // threads/threadid.c 11-1 #include "apue.h" #include <pthread.h> pthread_t ntid; void printids( const char * s) { printf ( "%d " , (unsigned int )ntid); printf ( "%ld " , (unsigned long )ntid); pid_t pid; pthread_t tid; pid = getpid(); tid = pthread_self(); // printf("%s pid %u tid %u (0x%x)\n", s, (unsigned int)pid, (unsigned int)tid, (unsigned int)tid); printf ( "%s pid %lu tid %lu (0x%lx)\n" , s, (unsigned long )pid, (unsigned long )tid, (unsigned long )tid); } void * thr_fn( void * arg) { printids( "new thread: " ); return (( void *)0); } /*This example has two oddities, which are necessary to handle races between the main * thread and the new thread. (We'll learn better ways to deal with these conditions later * in this chapter.) The first is the need to sleep in the main thread. If it doesn't sleep, the * main thread might exit, thereby terminating the entire process before the new thread * gets a chance to run. This behavior is dependent on the operating system's threads * implementation and scheduling algorithms. * The second oddity is that the new thread obtains its thread ID by calling * pthread_self instead of reading it out of shared memory or receiving it as an * argument to its thread-start routine. Recall that pthread_create will return the * thread ID of the newly created thread through the first parameter (tidp). In our * example, the main thread stores this ID in ntid, but the new thread can¡¯t safely use it. * If the new thread runs before the main thread returns from calling pthread_create, * then the new thread will see the uninitialized contents of ntid instead of the thread ID. */ int main( void ) { int err; err = pthread_create(&ntid, NULL, thr_fn, NULL); if (0 != err) err_quit( "can't create thread: %s\n" , strerror (err)); printids( "main thread:" ); sleep(1); return 0; } |
1 | |
1 2 3 4 5 | all: threadid threadid: threadid.c g++ -g -Wall threadid.c ../lib/libapue.a -I ../include -lpthread -o threadid clean: rm threadid |
1 | |
这和我在虚拟机centos6.3中测试的情况不同,centos下进程ID是相同的(3607),并不是不同的。
分类:
UNIX环境高级编程第二版
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· .NET制作智能桌面机器人:结合BotSharp智能体框架开发语音交互
· 软件产品开发中常见的10个问题及处理方法
· .NET 原生驾驭 AI 新基建实战系列:向量数据库的应用与畅想
· 从问题排查到源码分析:ActiveMQ消费端频繁日志刷屏的秘密
· 一次Java后端服务间歇性响应慢的问题排查记录
· 互联网不景气了那就玩玩嵌入式吧,用纯.NET开发并制作一个智能桌面机器人(四):结合BotSharp
· 一个基于 .NET 开源免费的异地组网和内网穿透工具
· 《HelloGitHub》第 108 期
· Windows桌面应用自动更新解决方案SharpUpdater5发布
· 我的家庭实验室服务器集群硬件清单