1、线程标识
#includepthread_t pthread_self(void); 功能:获取调用线程的线程id 返回值:调用线程的线程id int pthread_equal(pthread_t t1, pthread_t t2); 功能:比较线程id 返回值:若成功,返回非0数值;若失败,返回0
说明:1、Linux 3.2.0使用无符号长整型表示pthread_t数据类型;Solaris 10使用无符号整型表示pthread_t;FreeBSD 8.0用一个指 向pthread结构的指针表示pthread_t,因此不能用一种可移植的方式打印该数据类型的值。
2、创建线程
#includeint pthread_create(pthread_t *thread, const pthread_attr_t *attr, void *(*start_routine) (void *), void *arg); 功能:创建线程 参数: thread:保存新创建线程的线程id; attr:指定线程属性,当值为NULL时,使用默认属性创建线程; start_routine:新创建线程从该函数开始运行; arg:start_routine函数调用时,传递给start_routine函数 返回值:若成功,返回0;若失败,返回错误编号
3、创建线程实例
功能说明:打印进程id,新创建线程id,初始线程id
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:"); // 调用printids打印新创建线程id
return ((void *)0);
}
int main(void)
{
int err;
err = pthread_create(&ntid, NULL, thr_fn, NULL);
if (err != 0) {
printf("can't create threadn");
return err;
}
printids("main thread:"); // 调用printids打印初始线程id
sleep(1); // 睡眠1s,避免新线程未执行进程就结束
return 0;
}
在Ubuntu 16.04运行结果如下:
main thread: pid 2129 tid 3084171008 (0xb7d4b700) new thread: pid 2129 tid 3084168000 (0xb7d4ab40)
4、线程终止
#includevoid pthread_exit(void *retval); 功能:终止调用线程,并将retval的值发出,可使用pthread_join获得该值 #include int pthread_join(pthread_t thread, void **retval); 功能:调用线程阻塞直到指定线程退出 参数: thread:指定线程的线程id; retval:指定线程的返回信息; 返回值:若成功,返回0;若失败,返回错误编码 #include int pthread_cancel(pthread_t thread); 功能:向指定线程发送取消请求,指定线程可执行,也可不执行 参数: thread:指定线程的线程id; 返回值:若成功,返回0;若失败,返回错误编码



