zoukankan      html  css  js  c++  java
  • linux高编线程-------线程的创建,终止

    Q: what is thread  ?

    A:一个正在运行的函数----是运行函数咯----多线程共享内存空间咯

    posix线程是一套标准,而不是实现

    线程标识: pthread_t 类型不确定:结构体?or指针?or整型数,想啥是啥,可以自己定义咯

    lhh@lhh:~$ ps axm   
    lhh@lhh:~$ ps ax -L    // LWP

    进程就是容器  内部装载线程

    函数:

    int pthread_equal(pthread_t t1, pthread_t t2);//比较两个线程是否相同;相同返回非0  否则返回0
    pthread_t pthread_self(void); //返回当前线程标识;

    1.创建一个线程:

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

    参数1:回填线程表示

    参数2:线程的属性:常用NULL

    参数3:函数指针 ----兄弟线程

    参数4:兄弟线程的参数

    返回值:成功返回0;失败直接返回error number

    2.线程的终止:

          3种方式:1)线程从启动例程返回,返回值就是线程的退出码

                          2)线程可以被同一进程中的其他线程取消

                          3)线程调用pthread_exit()函数

    void pthread_exit(void *retval);//线程终止
    int pthread_join(pthread_t thread, void **retval);//线程收尸 成功返回0,错误返回error number  **retval只收尸不关心状态

    3.栈的清理:

         //钩子函数
           void pthread_cleanup_push(void (*routine)(void *),void *arg);
           void pthread_cleanup_pop(int execute);

    eg:

    #include <pthread.h>
    #include <string.h>
    static void *func(void *p) 
    {
        puts("Thead is working!");
        pthread_exit(NULL);
    }
    
    int main()
    {
        pthread_t tid;
        int err;
        puts("Begin !");
        err = pthread_create(&tid,NULL,func,NULL);
        if(err)
        {   
            fprintf(stderr,"%s",strerror(err));
            exit(1);
        }   
        pthread_join(tid,NULL);
        puts("End !");
        exit(0);
    }
    View Code

    OK!休息休息,下节继续!

     eg:

    #include <stdio.h>
    #include <stdlib.h>
    #include <pthread.h>
    #include <string.h>
    
    void *cleanup_func(void *p) 
    {
        puts(p);
    }
    
    void *func(void *p) 
    {
        puts("Thead is working !");
        pthread_cleanup_push(cleanup_func , "cleanup:1");
        pthread_cleanup_push(cleanup_func , "cleanup:2");
        pthread_cleanup_push(cleanup_func , "cleanup:3");
        pthread_cleanup_pop(1);
        pthread_cleanup_pop(0);
        pthread_cleanup_pop(1);
        pthread_exit(NULL);
    }
    
    int main()
    {
        pthread_t tid ;
        int err ;
        puts("Begin !");
        err = pthread_create(&tid,NULL,func,NULL);
        if(err)
        {   
            fprintf(stderr,"%s",strerror(err));
            exit(1);
        }   
            
        pthread_join(tid,NULL);
        exit(0);
    }
    View Code

    4.线程取消

    int pthread_cancel(pthread_t thread);//取消线程:正在运行的线程先取消再收尸
  • 相关阅读:
    shell
    RANDOM随机数
    docker网络管理
    Oracle-28001密码过期问题及28000账户被锁解决
    Oracle数据泵导入导出(expdb/impdb)
    mysql多实例部署
    sed命令基本使用
    MySQL5.7.x二进制安装
    每日日报
    每日日报
  • 原文地址:https://www.cnblogs.com/muzihuan/p/4694662.html
Copyright © 2011-2022 走看看