UNIX环境高级编程第11章线程

 

Y)]ICD@GDFRWELG04SI5V]X

 

Z~6QF84}N0LOMJAD(QK{`4G

 

GWNF97[]85}){@M(S276Q}E

 

9KK2WW(ENX~LZQ$LO_EGTUF

 

{~P61A6}9(_O4@}3R0ZHV12

 

OFPR))EAH9_BX1NEN9K@6TV

 

程序清单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
  

($96]3D7J`ID{YT2%ULYHBK

 

P_OH]47DHLP5(MN~8[CU_G5

 

这和我在虚拟机centos6.3中测试的情况不同,centos下进程ID是相同的(3607),并不是不同的。

K18O_03W)3Y1}P}YDN~XRG4

 

 

810de12d-73cc-45d0-928e-a7eb0766ea91

posted @   孙永杰  阅读(200)  评论(0编辑  收藏  举报
编辑推荐:
· .NET制作智能桌面机器人:结合BotSharp智能体框架开发语音交互
· 软件产品开发中常见的10个问题及处理方法
· .NET 原生驾驭 AI 新基建实战系列:向量数据库的应用与畅想
· 从问题排查到源码分析:ActiveMQ消费端频繁日志刷屏的秘密
· 一次Java后端服务间歇性响应慢的问题排查记录
阅读排行:
· 互联网不景气了那就玩玩嵌入式吧,用纯.NET开发并制作一个智能桌面机器人(四):结合BotSharp
· 一个基于 .NET 开源免费的异地组网和内网穿透工具
· 《HelloGitHub》第 108 期
· Windows桌面应用自动更新解决方案SharpUpdater5发布
· 我的家庭实验室服务器集群硬件清单
点击右上角即可分享
微信分享提示