linux下线程相关处理函数如下:
-----创建线程
int pthread_create(pthread_t *thread, const pthread_attr_t *attr,
void *(*start_routine) (void *), void *arg);
thread:若创建成功则保存被创建线程的线程句柄;
attr:线程属性;
start_routine:线程处理函数;
arg:线程处理函数参数;
返回值:0 创建成功 非零 创建失败
-----退出当前线程
void pthread_exit(void *retval);
retval:退出参数
-----等待某一线程退出
等待某一指定的线程退出,若未退出则阻塞
int pthread_join(pthread_t thread, void **retval);
thread:被等待退出的线程句柄;
retval:保存退出参数;
返回值:0 成功 非零表示失败
例程:
创建一个线程周期打印10次自己的线程句柄。主线程在创建线程后也周期打印5次自己的线程句柄,打印结束后等待子线程结束。
#include <stdlib.h>
#include <stdio.h>
#include <pthread.h>
void* pthread_function(void *arg)
{
int i;
/* 子线程打印10次线程句柄 */
for(i=0; i<10; i++) {
printf("%lu:This is a new pthread:%d\n", pthread_self(), i);
sleep(1);
}
pthread_exit(NULL);
return NULL;
}
int main(void)
{
pthread_t threadid;
int i;
printf("%lu:create a new pthread\n", pthread_self());
/* 创建线程 */
if( pthread_create(&threadid, NULL, pthread_function, NULL) != 0 ) {
perror("pthread create");
exit(-1);
}
printf("%lu:create success:%lu\n", pthread_self(), threadid);
/* 主线程打印5次线程句柄 */
for(i=0; i<5; i++) {
printf("%lu:father:%d\n", pthread_self(), i);
sleep(1);
}
/* 等待子线程结束 */
printf("%lu:wait the new pthread\n", pthread_self());
if( pthread_join(threadid, NULL) != 0) {
perror("pthread join");
exit(-1);
}
printf("%lu:over\n", pthread_self());
return 0;
}
结果如下:
3075774208:create a new pthread
3075774208:create success:3075771200
3075774208:father:0
3075771200:This is a new pthread:0
3075774208:father:1
3075771200:This is a new pthread:1
3075774208:father:2
3075771200:This is a new pthread:2
3075774208:father:3
3075771200:This is a new pthread:3
3075774208:father:4
3075771200:This is a new pthread:4
3075774208:wait the new pthread
3075771200:This is a new pthread:5
3075771200:This is a new pthread:6
3075771200:This is a new pthread:7
3075771200:This is a new pthread:8
3075771200:This is a new pthread:9
3075774208:over