天天看点

Linux多线程2-1---创造新线程

一、线程的ID

Linux多线程2-1---创造新线程

pthread_t:结构体(FreeBSD5.2、Mac OS10.3)/unsigned long int(linux)

                /usr/include/bits/pthreadtypes.h

获取线程ID:pthread_self()

一个实例:获取主线程ID

点击(此处)折叠或打开

#include "apue.h"

int main()

{

    pid_t pid;

    pthread_t tid;

    pid = getpid();

    tid = pthread_self();

    printf("pid is %u, tid is %x\n", pid, tid);

    return 0;

}

思考:线程ID出了进程范围还有效吗?

二、创造新线程

Linux多线程2-1---创造新线程

int pthread_create(pthread_t *restrict tidp, 

                             const pthread_attr_t *restrict attr, 

                             void *(*start_routine)(void *), 

                             void *restrict arg)

第一个参数:新线程的id,如果成功则新线程的id回填充到tidp指向的内存

第二个参数:线程属性(调度策略,继承性,分离性...)

第三个参数:回调函数(新线程要执行的函数)

第四个参数:回调函数的参数

返回值:成功返回0,失败则返回错误码

编译时需要连接库libpthread

实例:创建线程,打印ID

程序框图

Linux多线程2-1---创造新线程

/*AUTHOR:    WJ

 *DATE:        2015-3-18

 *

 *getpid()            获取进程ID

 *pthread_self()    获取ID

 *int pthread_create(pthread_t *thread,

 *                     const pthread_attr_t *attr,

 *                     void *(*start_routine) (void *),

 *                 void *arg);

 *第一个参数,新线程id,创建成功系统回填

 *第二个参数,新线程到属性,NULL为默认属性

 *第三个参数,新线程到启动函数

 *第四个参数,传递给新线程

 */

void print_id(char *s)

    printf("%s pid is %u, tid is 0x%x\n", s, pid, tid);

void *thread_fun(void *arg)

    print_id(arg);

    return (void *)0;

    pthread_t ntid;

    int err;

    err = pthread_create(&ntid, NULL, thread_fun, "new thread");

    if(err != 0 )

    {

        printf("create new thread failed\n");

        return 0;

    }

    print_id("main thread :");

    sleep(2);

继续阅读