Unix 用Pthread_create 函数编程 小例子

参考https://blog.csdn.net/wallwind/article/details/6989513, 试试自己写个程序。

功能: 创建一个子线程,比较一下主线程和子线程所在的进程ID和个子的线程ID。

代码部分:

 test_pthread.c
#include <stdio.h>
#include <pthread.h>
pthread_t new_tid;
void printThread(const char* s)
{
    pid_t pid;
    pthread_t tid;
    pid = getpid();
    tid = pthread_self();
    printf("%s, pid is %lu, tid is %x \n", s, (unsigned long)pid, (unsigned long)tid);
}
void* entranThr(void* arg)
{
    printf("create a children thread\n");
    printThread("children thread");
}
void main()
{

    int err = 0;
    err = pthread_create(&new_tid, NULL, entranThr, NULL);
    pid_t pid;
    pthread_t tid;
    pid = getpid();
    tid = pthread_self();
    printf("main thread pid is %lu, tid is %x,new_tid is %x\n", (unsigned long)pid, (unsigned long)tid, (unsigned long)new_tid);
    sleep(5);
}

编译: cc test_pthread.c -lpthread

运行结果:

 ./a.out
main thread pid is 17603, tid is b77ac6c0,new_tid is b77abb70
create a children thread
children thread, pid is 17603, tid is b77abb70

总结:进程17603 下有两个线程,主线程0xb77ac6c0,子线程0xb77abb70.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值