#include <stdio.h>
#include <stdlib.h>
void *fun(void *s)
{
char *p;
int i = 0;
char *m;
p = (char *)s;
for(i = 0; i < 5; i++)
{
printf("this is pthread function %d\n", i);
sleep(1);
}
return NULL;
}
int main(void)
{
char buf[32] = "hello";
pthread_t tid;
int ret;
if((ret = pthread_create(&tid, NULL, fun, (void *)buf)) == -1)
{
printf("create failed!\n");
return -1;
}
sleep(1);
// pthread_join(tid,NULL);
return 0;
}
这段代码就是调用子线程打印几句话,当主线程中没有pthread_join函数的时候子线程并没有运行,查阅资料后得知pthread_join函数的功能类似于一个阻塞函数,跟线程中的wait函数类似,它会等待子线程结束以后才会继续执行下面的语句。因此如果换成sleep函数也可以达到相同的目的,只要子线程能在睡眠时间之内执行完成即可。
可以设置线程分离pthread_detached,这样线程在运行结束以后就会自动释放资源,不需要使用pthread_join来回收。