一、线程的ID
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出了进程范围还有效吗?
二、创造新线程
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
如果对软件测试有兴趣,想了解更多的测试知识,解决测试问题,以及入门指导,
帮你解决测试中遇到的困惑,我们这里有技术高手。如果你正在找工作或者刚刚学校出来,
又或者已经工作但是经常觉得难点很多,觉得自己测试方面学的不够精想要继续学习的,
想转行怕学不会的,都可以加入我们644956177。
群内可领取最新软件测试大厂面试资料和Python自动化、接口、框架搭建学习资料!
实例:创建线程,打印ID
程序框图
/*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为默认属性
*第三个参数,新线程到启动函数
*第四个参数,传递给新线程
*/
#include "apue.h"
void print_id(char *s)
{
pid_t pid;
pthread_t tid;
pid = getpid();
tid = pthread_self();
printf("%s pid is %u, tid is 0x%x\n", s, pid, tid);
}
void *thread_fun(void *arg)
{
print_id(arg);
return (void *)0;
}
int main()
{
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);
return 0;
}