UNIX(编程-线程处理):03---线程的创建(pthread_create)
一、格式
#include <pthread.h>
int pthread_create(pthread_t *restrict tidp,const pthread_attr_t *restrict attr,void *(*start_rtn)(void *), void *restrict arg);
返回值:
- 成功:返回0
- 出错:返回错误编号
参数
- 参数1:当pthread_create成功返回时,新创建的线程ID会被设置到tidp所指向的内存单元中
- 参数2:atrr参数用于定制各种不同的线程属性。值为NULL时,创建一个具有默认属性的线程
- 参数3:新创建的线程从start_rtn函数的地址开始运行,该函数只有一个无类型指针参数arg
- 参数4:如果需要向start_rtn函数传递的参数有一个以上,需要把这些参数放到一个结构中,传递该结构的地址
注意事项:
- 线程创建时并不能保证哪个线程先运行:是新创建的线程,还是调用线程
- 新创建的线程可以访问进程的地址空间,并且继承调用线程的浮点环境和信号屏蔽字,但是该线程的挂起信号集会被清除,即被原线程阻塞之后收到的信号集不会被新线程继承
二、演示案例
#include<pthread.h>
#include<stdio.h>
#include<stdlib.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)
printf("can’t create thread\n");
printids("main thread:");
sleep(1);
exit(0);
}
运行结果:
- 注意事项:尽管Linux线程的ID用无符号长整型表示,但是看起来像指针