当前位置:   article > 正文

pthread_create创建线程_pthread_create创建线程无界面

pthread_create创建线程无界面

        什么是线程?

  • 轻量级的进程(LWP:light weight process),在Linux环境下线程的本质仍是进程。
  • 进程:拥有独立的地址空间,拥有PCB,相当于独居
  • 线程:有PCB,但没有独立的地址空间,多个线程共享进程空间,相当于合租

 

线程是系统调度进程执行的最小单位。

实际上,无论是创建进程的fork,还是创建线程的pthread_create,底层实现都是调用同一个内核函数 clone。

  • 如果复制对方的地址空间,那么就产出一个“进程”;
  • 如果共享对方的地址空间,就产生一个“线程”。

 因此Linux内核是不区分进程和线程的, 只在用户层面上进行区分

 所以,线程所有操作函数 pthread_* 是库函数,而非系统调用。

        

线程优、缺点

  • 优点:
    • 提高程序并发性
    • 开销小
    • 数据通信、共享数据方便
  • 缺点:
    • 库函数,不稳定
    • gdb调试、编写困难
    • 对信号支持不好

优点相对突出,缺点在接受范围之内。Linux下由于实现方法导致进程、线程差别不是很大。

——————————————————————————————————————————

对线程的创建使用 pthread_create函数

  • 函数作用:创建一个新线程
  • 函数原型int pthread_create(pthread_t *thread, const pthread_attr_t *attr,void *(*start_routine)(void *),void *arg);
  • 返回值:成功->返回0,失败返回错误号
  • 函数参数:
  1. pthread_t *thread:传出参数,pthread_t表示数据类型,保存系统为我们分配好的线程ID
  2. attr:通常传NULL,表示使用线程默认属性。若想使用具体属性也可以修改该参数。
  3. start_routine:函数指针,指向线程主函数(线程体),该函数运行结束,则线程结束。
  4. arg:线程主函数执行期间所使用的参数。

以一个例子引入

        编写程序创建一个线程,并给线程传递一个结构体参数

代码如下:

  1. //创建子线程
  2. #include <stdio.h>
  3. #include<iostream>
  4. #include <stdlib.h>
  5. #include <string.h>
  6. #include <sys/types.h>
  7. #include <unistd.h>
  8. #include <pthread.h>
  9. using namespace std;
  10. struct We
  11. {
  12. int data;
  13. string name;
  14. };
  15. //子进程处理函数
  16. void *mypthread(void *val)
  17. {
  18. cout << "child thread, pid==" << getpid() << ", id==" << pthread_self() << endl;
  19. struct We *p=(struct We*)val;
  20. cout<<"w->data:"<<p->data<<endl;
  21. cout<<"w->name:"<<p->name<<endl;
  22. }
  23. int main()
  24. {
  25. struct We w;
  26. w.data=51816;
  27. w.name="ZH&DQ";
  28. //函数原型
  29. //int pthread_create(pthread_t *thread, const pthread_attr_t *attr,
  30. // void *(*start_routine) (void *), void *arg);
  31. pthread_t thread;
  32. int ret=pthread_create(&thread,NULL,mypthread,&w);
  33. if(ret!=0)
  34. {
  35. cout<<"pthread_create error,"<<strerror(ret)<<endl;
  36. return -1;
  37. }
  38. //为了让子进程运行起来
  39. sleep(2);
  40. cout << "main thread, pid==" << getpid() << ", id==" << pthread_self() << endl;
  41. return 0;
  42. }

 执行结果如下:成功创建了子线程,并且子线程成功接收到主线程传递的结构体内容。

 

本文内容由网友自发贡献,转载请注明出处:【wpsshop博客】
推荐阅读
相关标签
  

闽ICP备14008679号