C多线程常用API操作

1 线程的标识

头文件

#include<pthread.h>

函数原型

pthread_tpthread_self(void);

返回值

成功:返回线程号

参数列表

#include<pthread.h>
#include<unistd.h>
#include<stdio.h>
int main()
{
    pid_tpid;
    pthread_ttid;

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

    printf("pid=%d,tid=%lu\n",(int)pid,(unsignedlong)tid);
    return0;
}

 2 线程的创建

pthread_create函数用于线程创建

头文件

#include<pthread.h>

函数原型

intpthread_create(pthread_t*thread,constpthread_attr_t*attr,void*(*start_routine)(void*),void*arg)

返回值

成功:0;失败:错误码 

参数列表

pthread_t*thread:线程id

constpthread_attr_t*attr:线程属性,NULL(由系统分配属性)

void*(*start_routine)(void*):线程执行函数

void*arg:线程创建时传递的参数,不传递时写NULL

 创建一个线程,并通过第一个参数将子线程号返回给主线程

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

void*first_func(void*arg)
{
    intret=0;
    int i;    
    printf("firstpthread,pid=%d,first_tid=%lu\n",(int)getpid(),(unsignedlong)pthread_self());

    return(void*)ret;

}

intmain()
{
    int err;
    pid_tpid;
    pthread_ttid,first_tid;
    /*创建第一个子线程*/
    err=pthread_create(&first_tid,NULL,(void*)first_func,NULL);
    if(err!=0)
    {
        printf("failtocreatapthread\n");
        return-1;
    }
    printf("mainpthread,pid=%d,tid=%lu\n",(int)pid,(unsignedlong)tid);
    /*主线程中打印第一子线程ID号*/
    printf("mainpthread,firstpthreadtid=%lu\n",(unsignedlong)first_tid);

    while(1);
    return 0;
}

 后续添加...

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值