【Linux】线程的创建

线程ID

类似于进程ID,线程ID用于表示线程,使用类型pthread_t来表示。
该类型在不同的系统中实现的方式也不相同,Linux中使用无符号长整型,而在其他实现中可能使用结构指针,所以考虑到可移植性,对于该类型尽量不要直接当整型来处理。

pthread_self函数

原型:
pthread_t pthread_self(void);
功能:返回调用线程的线程ID

线程的创建

创建线程使用pthread_create函数

原型:
int pthread_create(pthread_t *restrict tidp,
        const pthread_attr_t *restrict attr,
        void *(*start_rtn)(void*), void *restrict arg);
    返回值:成功则返回0,否则返回错误编号

功能:

  • 函数成功返回时,新建线程ID置为tidp所指内存。
  • attr用于定制不同的线程属性,NULL为默认属性。
  • 新创建的线程从start_rtn函数的地址开始运行,该函数只有一个无类型指针参数,若要传入函数start_rtn的参数有一个以上,则可以通过一个结构体来传入,参数arg可以用来传递该结构的指针。

    注意:

  • 线程建立时不保证哪个线程先运行。
  • 新建线程可以访问进程的地址空间,并继承调用线程的浮点环境和信号屏蔽字,但该线程的挂起信号集会被清除。
  • pthread_create函数出错时会返回错误码,而不是通过设置errno的方式。然而每个线程中都会提供errno的副本,为了与使用errno的函数兼容。

    下面给出一个创建线程并打印线程ID的例子

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>

pthread_t ntid;

void printids(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 *thrd_f(void *args)
{
    printids("new thread: ");
    return NULL;
}

int main()
{
    int err;

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

输出

main thread:  pid 20801 tid 139702766331648 (0x7f0f15c2e700)
new thread:  pid 20801 tid 139702758016768 (0x7f0f15440700)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值