LINUX线程简介和简单代码案例

0x00.什么是线程
    是计算机中独立运行的最小单位,运行时占用很少的系统资源。可以把线程看成是操作系统分配CPU时间的基本单元。一个进程可以拥有一个至多个线程。它线程在进程内部共享地址空间、打开的文件描述符等资源。同时线程也有其私有的数据信息,包括:线程号、寄存器(程序计数器和堆栈指针)、堆栈、信号掩码、优先级、线程私有存储空间

 

0x01.为什么使用线程
    在某个时间片需要同时执行两件或者两件以上的事情

0x02.怎么使用线程

   A. 使用到的函数

    int pthread_create(pthread_t *thread, const pthread_attr_t *attr,void *(*start_routine) (void *), void *arg);
    
    int pthread_join(pthread_t thread, void **retval);

  B.代码案例

  测试环境:ubuntu 16.0

  编译器:       g++ (Ubuntu 5.4.0-6ubuntu1~16.04.4) 5.4.0 20160609 (查看版本指令:g++ --version)

  编译注意事项: g++ thread.cpp -o thread -lpthread

 1     #include <stdio.h>
 2     #include <stdlib.h>
 3     #include <string.h>
 4     #include <error.h>
 5     #include <pthread.h>
 6     
 7     //要执行的线程方法
 8     void* ThreadFunc(void* argc)
 9     {
10         printf("thread start \n");
11     }
12     
13     int main(int argc,char* argv[])
14     {
15         pthread_t pid;
16         void* ret_val;
17         
18         //创建子线程并绑定子线程执行方法
19         int create_status = pthread_craete(&pthread_t, NULL,
20                 ThreadFunc, NULL);
21         if(0 != create_status)
22         {
23             perror("main()->pthread_create");
24             exit(1);
25         }
26         
27         //等待创建的子线程先执行
28         pthread_join(pid, &ret_val);
29         
30         return 0;
31     }

 

0x03.遇到的坑

      先没有使用pthread_join(),执行./thread 没有任何信息。后来查资料了解到 pthread_create() 创建线程成功后,主线程(main())会继续执行。

      之后调用pthread_join()函数,会等待子线程执行完毕,再继续主线程。

 

 


  

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值