【APUE】8、pthread_create函数,创建子线程

函数定义,已经相应的头文件

#include <pthread.h>

 

int pthread_create(pthread_t *thread, constpthread_attr_t *attr,

                          void*(*start_routine) (void *), void *arg);

 

创建线程

 

注意编译的时候link上-pthread.

/**
 * 功能:创建一个线程
 * 时间:2015年12月26日17:00:36
 * 作者:cutter_point
 */
#include "../util/apue.h"
#include "../util/error.c"

#include <pthread.h>

pthread_t ntid;  //the thread id

//打印进程ID和线程id
void printids(const char *s)
{
    pid_t pid;  //进程id
    pthread_t tid;
    //get process id
    pid = getpid();
    //get thread id
    sleep(1);
    tid = pthread_self();
    //out put
    printf("%s\t pid:%lu\ttid:%lu\t(0x)%lx\n", s, (unsigned long)pid,
                                               (unsigned long)tid, (unsigned long)tid);
}

void test();

//the thread begin
void * thr_fn(void *arg)
{
    printids("new thread:");
    test();
    return ((void*)0);
}

//my test if thread begin include this?
void test()
{
    printf("just test for thread where it begin!\n");
}

int main(int argc, char *argv[])
{
    int err;    //if create thread fail return this number
    err = pthread_create(&ntid, NULL, thr_fn, NULL);
    if(err != 0)
        err_exit(err, "can`t create new thread");

    printids("main thread:");

    sleep(1);   //this is because if main stop the thread have no chance to begin

    exit(0);
}


我们在Linux中编译

 

gcc -pthread -gthreadid.cpp -o threadid.out




我们的进程id是一样的,说明这两段程序执行的时候是在同一个进程中的,但是后面的线程id是不一样的,原因是:主线程吧新线程的id存放在ntid中,当主线程获取相应的线程id的时候,新线程在主线程调用pthread_create返回直线就执行了,那么新线程得到的是还没有初始化的id




















评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值