apue学习之线程创建

来源:互联网 发布:天狼月季姜正之淘宝店 编辑:程序博客网 时间:2024/04/30 19:42

线程标识:

每个进程有一个进程ID,每一个线程也有一个线程ID,进程ID在系统中是唯一的,,线程ID不同,它只在所属的进程环境中才有效。

pthread_t在不同的系统中实现是不一样的,mac系统中它是一个结构体类型指针,所以要用函数来比较两个线程是否是一个线程。

#include <pthread.h>int pthread_equal(<pthread_t tid1>, <pthread_t tid2>);

线程可以通过函数获得自身的id;
#include <pthread.h> pthread_t pthread_self();
线程的创建:

每一个线程都可以创建其他线程。用pthread_create();

#include <pthread.h>int pthread_create(pthread_t *restrict tidp, const pthread_addr_t *restrict attr, void *(*start_rtn)(void *), void *restrict arg);
tidp指向新建的线程ID,attr定制各种不同线程的属性,start_rtn线程调用的执行线程的函数,如果strat_rtn函数有不止一个参数,那应该放到一个结构体中,

把结构体地址放到arg中传入。


联系实例:

#include <stdio.h>#include <pthread.h>#include "apue.h"pthread_t ntid;                    //pthread_t是一个结构体类型的指针void printids(const char *s);void *thr_fn(void *arg);void printids(const char *s){    pid_t pid;                      //pid_t   int整型变量    pthread_t tid;        pid = getpid();    tid = pthread_self();    printf("%s pid %u tid %u (0x%x)\n",s,(unsigned int)pid,(unsigned int)tid,(unsigned int)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 : %s\n",strerror(err));    }    printids("main thread:");    sleep(1);                             //主线程要休眠,如果主线程不休眠,可能线程没来得及执行就因为主线程推出而终止了。    return 0;}


这个程序两个要点注意:主线程要sleep,确保子线程运行。第二个是通过pthread_self知道线程id,而不用全局变量ntid,这是因为不确定线程函数执行时主线程pthread_create()函数返回。

原创粉丝点击