使用pthread_create()创建线程

可以通过 pthread_create()函数创建新线程。

#include <pthread.h>
int pthread_create(pthread_t *restrict tidp,
                              const pthread_attr_t *restrict attr,
                              void *(*start_rtn)(void *),
                              void *restrict arg);

返回值:
若成功,返回0;否则,返回错误编码

参数说明:

  • tidp:新创建的线程ID会被设置成tidp指向的内存单元。
  • attr:用于定制各种不能的线程属性,默认为NULL
  • start_rtn:新创建的线程从start_rtn函数的地址开始运行,该函数只有一个void类型的指针参数即arg,如果start_rtn需要多个参数,可以将参数放入一个结构中,然后将结构的地址作为arg传入。

pthread函数在调用失败后通常会返回错误码,但不会设置errno

我们看下面一个例子,该示例中,程序创建了一个线程,打印了进程ID、新线程的线程ID以及初始线程的线程ID。

#include <pthread.h>

pthread_t ntid;

void printids(const char *s)
{
    pid_t   pid;
    pthread_t   tid;
    
    pid = getpid();
    tid = pthread_self();

    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);
}

int main()
{
    int     err;
    
    err = pthread_create(&ntid, NULL, thr_fn, NULL);
    if(err!=0)
    {
        printf("can't create thread\n");
        exit(1);
    }
    printids("main thread:");
    sleep(2);
    exit(0);
}

运行结果如下:

main thread: pid 13019 tid 139937898653440 (0x7f45d4bd6700)
new thread: pid 13019 tid 139937890158336 (0x7f45d43bc700)

正如我们的期望,进程ID相同10310,线程ID不同。

主线程如果不休眠,有可能在新线程执行之前就退出了。

如下是去掉后的再次执行结果,很明显,第一次执行时,新线程没有机会运行:

➜  tmp ./pt
main thread: pid 13113 tid 139742167656192 (0x7f1842436700)
➜  tmp ./pt
main thread: pid 13119 tid 139768977393408 (0x7f1e803f8700)
new thread: pid new thread: pid 13119 tid 139768968922880 (0x7f1e7fbe4700)

上面示例中,我们使用pthread_self()函数获得线程的ID

转载于:https://www.cnblogs.com/biggerman/p/6940888.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值