zoukankan      html  css  js  c++  java
  • linux 线程

    线程的概念

    • 1、线程是进程内部的一个执行分支,线程量级很小。(所谓的内部就是在进程的地址空间内运行)
    • 2、一切进程至少都有一个线程

    线程和进程的区别

    • 进程是资源竞争的基本单位
    • linux下没有真正意义的线程,因为linux下没有给线程设计专有的结构体,它的线程是用进程模拟的,而它是由多个进程共享一块地址空间而模拟得到的。
    • 创建一个线程的资源成本小,工作效率高
    • Linux下cpu所看到的所以进程都可以看成轻量级的进程
    • 进程是承担分配系统资源的基本实体,进程具有独立性(但进程间通信打破了独立性)
    • 线程是cpu或操作系统调度的基本单位,线程具有共享性

    线程共享的资源

    • 同一块地址空间
    • 数据段
    • 代码段
    • 堆区
    • 动态库加载区

    线程独立的资源

    • 线程会产生临时变量,临时变量保存再栈上,所以每个线程都有自己的私有栈结构
    • 每个线程都有私有的上下文信息。
    • 线程ID
    • 一组寄存器的值
    • errno变量
    • 信号屏蔽字以及调度优先级

    查看线程的LWP号(线程号)

    • 找到进程ID(pid)
    • ps -Lf pid

    创建线程

    pthread_create函数

    int pthread_create(
        pthread_t *thread,    //线程ID
        const pthread_attr_t *attr,      //线程属性
        void *(*start_routine)(void *),       //线程处理函数
        void *arg     //线程处理函数参数
    //返回值:若成功则返回0,否则返回出错编号

    创建一个子线程:

    #include <stdio.h>
    #include <unistd.h>
    #include <pthread.h>
    
    void *myfunc(void * arg)
    {
            printf("child thread id: %lu
    ", pthread_self());
            return NULL;
    }
    
    int main(int argc, const char* argv[])
    {
            pthread_t pthid;
            pthread_create(&pthid, NULL, myfunc, NULL);
            printf("parent thread id: %lu
    ", pthread_self());
    
            printf("xmm
    ");
            sleep(2);
            return 0;
    }
    View Code

    循环创建多个子线程:

    #include <stdio.h>
    #include <unistd.h>
    #include <pthread.h>
    
    void *myfunc(void * arg)
    {
            int num = (int)arg;
            printf("child thread %d id: %lu,
    ", num, pthread_self());
            return NULL;
    }
    
    int main(int argc, const char* argv[])
    {
            pthread_t pthid[5];
            int i;
            for(i=1; i<=5; i++)
            {
                    pthread_create(&pthid[i], NULL, myfunc, (void*)i);
            }
            printf("parent thread id: %lu
    ", pthread_self());
    
            printf("xmm
    ");
            sleep(2);
            return 0;
    }
    View Code

    打印错误信息:

    int ret = pthread_create(&pthid, NULL, myfunc, NULL);
    if(ret != 0)
    {
      printf("%s
    ", strerror(ret));  
    }
    View Code

    退出线程

    pthread_exit

    void pthread_exit( void * retval );

    参数:

    retval是函数的传出参数,只要pthread_join中的第二个参数value_ptr不是NULL,这个值将被传递给value_ptr

    pthread_join

    函数原型:

    int pthread_join(pthread_t pthread, void **retval);

    功能:

    • 阻塞等待线程退出

    参数:

    • pthread:要回收的子线程的线程id
    • retval:子线程退出的时候携带的状态信息
  • 相关阅读:
    序列化
    输入输出流——字符流部分
    输入输出流——字节流部分
    GitHub10岁之际HanLP自然语言处理包用户量跃居榜首
    hadoop大数据处理平台与案例
    dkhadoop的自然语言处理技术介绍
    hadoop大数据技术架构详解
    hadoop框架结构介绍
    Hadoop集群环境搭建步骤说明
    快速了解掌握中文自然语言处理
  • 原文地址:https://www.cnblogs.com/xumaomao/p/13095070.html
Copyright © 2011-2022 走看看