1 相关的API
#include <pthread.h>*
**int pthread_create(pthread_t *thread, const pthread_attr_t *attr, void *(*start_routine) (void ), void arg);
-
pthread_t
-
参1:传出参数,表新创建的子线程 id
-
参2:线程属性。传NULL表使用默认属性。
-
参3:子线程的回调函数是一个返回值是泛型指针的函数。创建成功,ptherad_create函数返回时,该函数会被自动调用。是一个指向函数指针的指针。
-
参4:参3的参数。没有的话,传NULL
-
返回值:成功:0
失败:errno -
示例
pthread_create(&tid, NULL, tfn, NULL)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>
#include <pthread.h>
void sys_err(const char *str){
perror(str);
exit(1);
}
void *tfn(void *arg){
printf("thread: pid = %d, tid = %lu\n", getpid(), pthread_self());
return NULL;
}
int main(int argc, char *argv[]){
pthread_t tid;
printf("main: pid = %d, tid = %lu\n", getpid(), pthread_self());
int ret = pthread_create(&tid, NULL, tfn, NULL);
if (ret != 0) {
perror("pthread_create error");
}
return 0;
}
*void pthread_exit(void retval); 退出当前线程
-
retval:退出值。 无退出值时,NULL
-
exit(); 退出当前进程。
-
return: 返回到调用者那里去。
-
pthread_exit(): 退出当前线程。
int pthread_join(pthread_t thread, void retval); 阻塞 回收线程。
-
thread: 待回收的线程id
-
retval:传出参数。 回收的那个线程的退出值。
-
线程异常借助,值为 -1。
-
返回值:成功:0
-
失败:errno
示例
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>
#include <pthread.h>
struct thrd {
int var;
char str[256];
};
void sys_err(const char *str)
{
perror(str);
exit(1);
}
void *tfn(void *arg)
{
struct thrd *tval;
tval = malloc(sizeof(tval));
tval->var = 100;
strcpy(tval->str, "hello thread");
return (void *)tval; (将一个指针转化成一个泛型指针)
}
int main(int argc, char *argv[])
{
pthread_t tid;
struct thrd *retval;
int ret = pthread_create(&tid, NULL, tfn, NULL);
if (ret != 0)
sys_err("pthread_create error");
//int pthread_join(pthread_t thread, void **retval);
ret = pthread_join(tid, (void **)&retval);
if (ret != 0)
sys_err("pthread_join error");
printf("child thread exit with var= %d, str= %s\n", retval->var, retval->str);
pthread_exit(NULL);
}
int pthread_cancel(pthread_t thread); 杀死一个线程。 需要到达取消点(保存点)
thread: 待杀死的线程id
返回值:成功:0
失败:errno
如果,子线程没有到达取消点, 那么 pthread_cancel 无效。
我们可以在程序中,手动添加一个取消点。使用 pthread_testcancel();
成功被 pthread_cancel() 杀死的线程,返回 -1.使用pthead_join 回收。
int pthread_detach(pthread_t thread); 设置线程分离
-
thread: 待分离的线程id
-
返回值:成功:0
-
失败:errno
2 线程与进程的对比
线程控制原语 | 进程控制原语 |
---|---|
pthread_create() | fork() |
pthread_self() | getpid() |
pthread_exit() | exit() |
pthread_join | wait()/waitpid() |
pthread_cancel() | kill() |
pthread_detach() |