线程ID
类似于进程ID,线程ID用于表示线程,使用类型pthread_t来表示。
该类型在不同的系统中实现的方式也不相同,Linux中使用无符号长整型,而在其他实现中可能使用结构指针,所以考虑到可移植性,对于该类型尽量不要直接当整型来处理。
pthread_self函数
原型:
pthread_t pthread_self(void);
功能:返回调用线程的线程ID
线程的创建
创建线程使用pthread_create函数
原型:
int pthread_create(pthread_t *restrict tidp,
const pthread_attr_t *restrict attr,
void *(*start_rtn)(void*), void *restrict arg);
返回值:成功则返回0,否则返回错误编号
功能:
- 函数成功返回时,新建线程ID置为tidp所指内存。
- attr用于定制不同的线程属性,NULL为默认属性。
新创建的线程从start_rtn函数的地址开始运行,该函数只有一个无类型指针参数,若要传入函数start_rtn的参数有一个以上,则可以通过一个结构体来传入,参数arg可以用来传递该结构的指针。
注意:
- 线程建立时不保证哪个线程先运行。
- 新建线程可以访问进程的地址空间,并继承调用线程的浮点环境和信号屏蔽字,但该线程的挂起信号集会被清除。
pthread_create函数出错时会返回错误码,而不是通过设置errno的方式。然而每个线程中都会提供errno的副本,为了与使用errno的函数兼容。
下面给出一个创建线程并打印线程ID的例子
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
pthread_t ntid;
void printids(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 *thrd_f(void *args)
{
printids("new thread: ");
return NULL;
}
int main()
{
int err;
err = pthread_create(&ntid, NULL, thrd_f, NULL);
if(err != 0){
printf("can't create pthread\n");
exit(1);
}
printids("main thread: ");
sleep(1);
return 0;
}
输出
main thread: pid 20801 tid 139702766331648 (0x7f0f15c2e700)
new thread: pid 20801 tid 139702758016768 (0x7f0f15440700)
664

被折叠的 条评论
为什么被折叠?



