线程的创建
#include < pthread. h>
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函数开始运行,该函数只有一个无类型指针参数arg。
如果需要向start_rtn函数传递不止一个参数,需要把这些参数放到一个结构体上,然后把这个结构的地址作为参数传入,不需要参数时,传入NULL。
注意:
线程创建时并不能保证是哪个线程会先运行:是新创建的线程,还是调用的线程。新创建的线程可以访问进程的地址空间,并且继承调用线程的浮点环境和信号屏蔽字,但是该线程的挂起信号集会被清除。
实例
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>
pthread_t ntid;
void printids(const char *s){
pid_t pid;
pthread_t tid;
pid = getpid();//获取进程ID
tid = pthread_self();//获取调用线程ID
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(int argc, const char * argv[]) {
int err;
err = pthread_create(&ntid, NULL, thr_fn, NULL);
if (err != 0) {
printf("can't create thread");
}
printids("main thread:");
sleep(1);
exit(0);
}
注意:这里要调用sleep来让子线程有时间执行,否则可能子线程还未执行,主线程就结束了,整个进程也结束了。