一、线程标识
和每个进程都有一个进程ID一样,每个线程也有一个线程ID,线程ID是以pthread_t数据类型来表示的,在Linux中,用无符号长整型表示pthread_t,Solaris 把phread_t数据类型表示为无符号整型,FreeBSD 和Mac OS X 用一个指向pthread结构的指针来表示pthread_t数据类型。
可以使用pthread_self函数获得自身的线程ID。
#include <pthread.h> pthread_t pthread_self(void);
二、线程创建
使用pthread_create函数创建新线程
#include <pthread.h> int pthread_create(pthread_t *restrict tidp, const pthread_arrt_t *restrict addr, void *(*start_rtn)(void *), void *restrict arg);
当pthread_create成功返回后,新创建线程的线程ID会被设置成tidp指向的内存单元,attr参数用于定制各种不同的线程属性,后面再讨论线程属性,现在先把它置为null,创建一个具有默认属性的线程。
新创建的线程从start_rtn函数开始运行,该函数接收一个无类型指针的参数arg,如果要传给它的参数多于一个,可以把参数放到一个结构中,然后把结构的地址作为arg传入。
线程新建后会继承调用线程的浮点环境和屏蔽字。
例子:
#include "apue.h" #include <pthread.h> pthread_t ntid; void printids(const char *s) { pid_t pid; pthread_t tid; pid = getpid(); tid = pthread_self(); 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(void) { int err; err = pthread_create(&ntid, NULL, thr_fn, NULL); if (err != 0) { err_exit(err, "can't create thread"); } printids("main thread: "); sleep(1); exit(0); }