Linux多线程2-1---创造新线程(持续更新)

3 篇文章 0 订阅
1 篇文章 0 订阅

一、线程的ID

在这里插入图片描述

pthread_t:结构体(FreeBSD5.2、Mac OS10.3)/unsigned long int(linux)
/usr/include/bits/pthreadtypes.h

获取线程ID:pthread_self()
一个实例:获取主线程ID

#include "apue.h"

int main()
{
    pid_t pid;
    pthread_t tid;

    pid = getpid();
    tid = pthread_self();

    printf("pid is %u, tid is %x\n", pid, tid);

    return 0;
}

思考:线程ID出了进程范围还有效吗?

二、创造新线程
在这里插入图片描述

int pthread_create(pthread_t *restrict tidp,
const pthread_attr_t *restrict attr,
void *(*start_routine)(void *),
void *restrict arg)
第一个参数:新线程的id,如果成功则新线程的id回填充到tidp指向的内存
第二个参数:线程属性(调度策略,继承性,分离性…)
第三个参数:回调函数(新线程要执行的函数)
第四个参数:回调函数的参数
返回值:成功返回0,失败则返回错误码
编译时需要连接库libpthread

如果对软件测试有兴趣,想了解更多的测试知识,解决测试问题,以及入门指导,
帮你解决测试中遇到的困惑,我们这里有技术高手。如果你正在找工作或者刚刚学校出来,
又或者已经工作但是经常觉得难点很多,觉得自己测试方面学的不够精想要继续学习的,
想转行怕学不会的,都可以加入我们644956177
群内可领取最新软件测试大厂面试资料和Python自动化、接口、框架搭建学习资料!

实例:创建线程,打印ID
程序框图
在这里插入图片描述

/*AUTHOR:    WJ
 *DATE:        2015-3-18
 *
 *
 *getpid()            获取进程ID
 *pthread_self()    获取ID
 *
 *int pthread_create(pthread_t *thread,
 *                     const pthread_attr_t *attr,
 *                     void *(*start_routine) (void *),
 *                 void *arg);
 *第一个参数,新线程id,创建成功系统回填
 *第二个参数,新线程到属性,NULL为默认属性
 *第三个参数,新线程到启动函数
 *第四个参数,传递给新线程
 */
#include "apue.h"

void print_id(char *s)
{
    pid_t pid;
    pthread_t tid;

    pid = getpid();
    tid = pthread_self();

    printf("%s pid is %u, tid is 0x%x\n", s, pid, tid);

}

void *thread_fun(void *arg)
{
    print_id(arg);
    return (void *)0;
}

int main()
{
    pthread_t ntid;
    int err;

    err = pthread_create(&ntid, NULL, thread_fun, "new thread");
    if(err != 0 )
    {
        printf("create new thread failed\n");
        return 0;
    }
    
    print_id("main thread :");
    sleep(2);

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值