您的位置:首页 > 其它

一篇带你完全掌握线程的博客

2018-09-21 09:11 597 查看
  前言:最近一直在疯狂学习,之前也不太了解线程,现在基本都掌握了。如果你之前也不知道线程,也不知道进程和线程的区别等等,这一篇博客带你完全掌握,不掌握不要钱,哈哈哈!

  一、线程概念

   介绍概念之前,先画个图吧,依旧是全博客园最丑图,不接受反驳!

  

#include<stdio.h>
#include<unistd.h>
#include<pthread.h>

void *tfn(void *arg)
{
printf("child thread%lu\n",pthread_self());
return NULL;
}

int main()
{
pthread_t tid;
pthread_create(&tid,NULL,tfn,NULL);
sleep(1);
printf("main thread:%lu\n",pthread_self());

return 0;
}


View Code
  编译:gcc pthread_cre.c -lpthread,记得链接线程库 -lpthread

  pthread_exit函数

  功能:将单个线程退出 相当于exit

  原型:void pthread_exit(void *retval);

  参数:retval表示线程退出状态,通常传NULL

  pthread_join函数

  功能:阻塞等待线程退出,获取线程退出状态 其作用,对应进程中 wait()、waitpid() 函数。

  原型:int pthread_join(pthread_t thread, void **retval);

  参数:thread:线程ID (【注意】:不是指针);retval:存储线程结束状态。

  pthread_detach函数

  功能:实现线程分离 线程独有的,没有进程的相关函数与之对应

  原型:int pthread_detach(pthread_t thread);

  线程分离状态:指定该状态,线程主动与主控线程断开关系。线程结束后,其退出状态不由其他线程获取,而直接自己自动释放。网络、多线程服务器常用。

  重点:分离状态的线程就不需要回收了!!!重要的事情说三遍,三遍,三遍!!!

  pthread_cancel函数

  功能:杀死(取消)线程 其作用,对应进程中 kill() 函数。

  原型:int pthread_cancel(pthread_t thread);

  【注意】:线程的取消并不是实时的,而有一定的延时。需要等待线程到达某个取消点(检查点)。

  六、控制原语对比

  就是就是将进程相关函数与线程函数,进行对比来记忆:

  进程 线程

fork pthread_create

exit pthread_exit

wait pthread_join

kill pthread_cancel

getpid pthread_self

  总结:欢迎评论,交流与学习。

  
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: