zoukankan      html  css  js  c++  java
  • linux多线程编程1

    线程基本概念以及优缺点:

    1、线程是操作系统执行任务的最小单位,进程是操作系统分配资源的最小单位。

    2、线程可以共享文件描述符表、每种信号的处理方式、当前的工作目录、用户ID以及组ID;

          线程id非共享,每个线程都拥有独立的栈空间(可以将每个线程看作一个函数),error变量非共享(每个errno是每个线程私有的值,可以通过 char *strerror(int errnum) 函数查看出错的原因)。

    3、线程优点:提高并发性、占用资源小、通信方便、开销小。

    linux线程的基本实现(包含文件头<pthread.h>,编译时需要加上-lpthread):

    1、线程的创建:创建线程通常使用的函数是pthread_create;

      函数原型:int pthread_create((pthread_t *thread, const pthread_attr_r *attr, void* (*start_routine)(void*), void *arg))

      函数传入值:thread:线程标识符,pthread_t标识无符号整数

            attr:线程属性,null表示默认属性(一般传null)

            start_routine:为一个函数指针,返回值为void*,可以看作线程的任务单元函数

            arg:传给函数的参数

      函数传出值:成功返回0,失败返回errno;

      线程id的获取:获取线程的id可以通过pthread_t pthread_self()来获取,相当于getpid();

    2、线程的退出:线程退出的方式

      函数原型:void pthread_exit(void *retval);

      函数传入值:retval:调用者线程的返回值,可由其他函数如pthread_join来检索获取。

      线程退出注意事项:

      1)线程中使用pthread_exit

      2)在线程中使用return(主控线程return表示退出整个进程)

      3)exit代表直接退出整个进程

    3、线程的回收

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

      函数传入值:thread:创建的时候传出的参数,tid

            retval:代表传出线程的退出信息(return value)

      函数作用:阻塞等待至该线程执行完。当函数返回时,被等待的线程资源就会被回收。

     4、杀死线程

      函数原型:int pthread_cancel(pthread_t thread)

      函数传入值:thread:创建线程传入的参数,tid

      返回值:失败返回errno,成功返回0;

      注意点:1)当用此方式杀死线程时,退出状态为-1;

          2)此方式杀死的线程必须有取消点,即不能杀死while(1)里面是空实现这样的线程;

    5、线程的分离

      函数原型:int pthread_detach(pthread_t thread);

      函数参数:thread:创建线程传入的参数,tid

      返回值:成功返回0, 失败返回errno

      注意点:1)线程分离类似于于进程脱离终端变为后台进程类似,当线程退出时,会自动回收线程资源,而如果不是分离状态,线程必须保留它的线程ID,退出状态直到其它线程对它调用了pthread_join。

    文章参考:

    https://www.cnblogs.com/skynet/archive/2010/10/30/1865267.html

  • 相关阅读:
    LeetCode 382. Linked List Random Node
    LeetCode 398. Random Pick Index
    LeetCode 1002. Find Common Characters
    LeetCode 498. Diagonal Traverse
    LeetCode 825. Friends Of Appropriate Ages
    LeetCode 824. Goat Latin
    LeetCode 896. Monotonic Array
    LeetCode 987. Vertical Order Traversal of a Binary Tree
    LeetCode 689. Maximum Sum of 3 Non-Overlapping Subarrays
    LeetCode 636. Exclusive Time of Functions
  • 原文地址:https://www.cnblogs.com/zz1314/p/12858089.html
Copyright © 2011-2022 走看看