码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2017-08-12 22:36:24      阅读:174      评论:0      收藏:0      [点我收藏+]

标签:read   地址空间   join()   案例   tin   creat   时间   计数器   系统   

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()函数,会等待子线程执行完毕,再继续主线程。

 

 


  

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

标签:read   地址空间   join()   案例   tin   creat   时间   计数器   系统   

原文地址:http://www.cnblogs.com/ReacherGua/p/7351573.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!