DoubleLi

qq: 517712484 wx: ldbgliet

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::
  4737 随笔 :: 2 文章 :: 542 评论 :: 1615万 阅读
< 2025年3月 >
23 24 25 26 27 28 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 1 2 3 4 5

include <stdio.h>

include <pthread.h>

include <sys/types.h>

include <sys/syscall.h>

struct message
{
int i;
int j;
};

void *hello(struct message *str)
{
printf("child, the tid=%lu, pid=%d\n",pthread_self(),syscall(SYS_gettid));
printf("the arg.i is %d, arg.j is %d\n",str->i,str->j);
printf("child, getpid()=%d\n",getpid());
while(1);
}

int main(int argc, char *argv[])
{
struct message test;
pthread_t thread_id;
test.i=10;
test.j=20;
pthread_create(&thread_id,NULL,hello,&test);
printf("parent, the tid=%lu, pid=%d\n",pthread_self(),syscall(SYS_gettid));
printf("parent, getpid()=%d\n",getpid());
pthread_join(thread_id,NULL);
return 0;
}
复制代码

getpid()得到的是进程的pid,在内核中,每个线程都有自己的PID,要得到线程的PID,必须用syscall(SYS_gettid);

pthread_self函数获取的是线程ID,线程ID在某进程中是唯一的,在不同的进程中创建的线程可能出现ID值相同的情况。

复制代码

include <stdio.h>

include <pthread.h>

include <stdlib.h>

include <unistd.h>

include <sys/syscall.h>

void *thread_one()
{
printf("thread_one:int %d main process, the tid=%lu,pid=%ld\n",getpid(),pthread_self(),syscall(SYS_gettid));
}

void *thread_two()
{
printf("thread two:int %d main process, the tid=%lu,pid=%ld\n",getpid(),pthread_self(),syscall(SYS_gettid));
}

int main(int argc, char *argv[])
{
pid_t pid;
pthread_t tid_one,tid_two;
if((pid=fork())-1)
{
perror("fork");
exit(EXIT_FAILURE);
}
else if(pid
0)
{
pthread_create(&tid_one,NULL,(void *)thread_one,NULL);
pthread_join(tid_one,NULL);
}
else
{
pthread_create(&tid_two,NULL,(void *)thread_two,NULL);
pthread_join(tid_two,NULL);
}
wait(NULL);
return 0;
}
复制代码

posted on   DoubleLi  阅读(281)  评论(0编辑  收藏  举报
编辑推荐:
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!
历史上的今天:
2016-04-28 linux 内核驱动编程 简单例子 与_IO, _IOR, _IOW, _IOWR 宏解析
2016-04-28 undefined reference to XXX 问题原因
点击右上角即可分享
微信分享提示