创建线程

线程的创建


#include < pthread. h>
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函数开始运行,该函数只有一个无类型指针参数arg。
如果需要向start_rtn函数传递不止一个参数,需要把这些参数放到一个结构体上,然后把这个结构的地址作为参数传入,不需要参数时,传入NULL。

注意:

线程创建时并不能保证是哪个线程会先运行:是新创建的线程,还是调用的线程。新创建的线程可以访问进程的地址空间,并且继承调用线程的浮点环境和信号屏蔽字,但是该线程的挂起信号集会被清除。

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

pthread_t ntid;

void printids(const char *s){
    pid_t pid;
    pthread_t tid;
    pid = getpid();//获取进程ID
    tid = pthread_self();//获取调用线程ID
    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 argc, const char * argv[]) {

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

注意:这里要调用sleep来让子线程有时间执行,否则可能子线程还未执行,主线程就结束了,整个进程也结束了。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值