zoukankan      html  css  js  c++  java
  • 多线程执行顺序诡异现象谈,你不知道的pthread_create

    引文:学而时习之,不亦说乎。总是忙于具体项目,业务功能的实现;关于编程本身的技能都要有些生疏了,于是就选择了几个专题做了一次温习,重点放在了多线程和多进程上,跑了一个实例,居然有新的发现:

    (1)多个线程顺序创建的顺序=线程执行顺序吗?

    (2)多个线程顺序创建,回调函数执行顺序有规律吗?

    示例

    #include "apue.h"
    #include <pthread.h>
    
    void *
    thr_fn1(void *arg)
    {
        printf("thread 1 returning
    ");
        return((void *)1);
    }
    
    void *
    thr_fn2(void *arg)
    {
        printf("thread 2 exiting
    ");
        pthread_exit((void *)2);
    }
    
    int
    main(void)
    {
        int            err;
        pthread_t    tid1, tid2;
        void        *tret;
    
        err = pthread_create(&tid1, NULL, thr_fn1, NULL);
        if (err != 0)
            err_quit("can't create thread 1: %s
    ", strerror(err));
        /*sleep(1);*/
        err = pthread_create(&tid2, NULL, thr_fn2, NULL);
        if (err != 0)
            err_quit("can't create thread 2: %s
    ", strerror(err));
        err = pthread_join(tid1, &tret);
        if (err != 0)
            err_quit("can't join with thread 1: %s
    ", strerror(err));
        printf("thread 1 exit code %d
    ", (int)tret);
        err = pthread_join(tid2, &tret);
        if (err != 0)
            err_quit("can't join with thread 2: %s
    ", strerror(err));
        printf("thread 2 exit code %d
    ", (int)tret);
        exit(0);
    }

    输出

    thread 2 exiting
    thread 1 returning
    thread 1 exit code 1
    thread 2 exit code 2

    讨论

      看到这个顺序是否有点意外,从多线程实现的机制来讲,这个顺序是没问题的,创建的过程不等于执行的过程,各种教科书都会这么告诉我们。可是我想知道的是,创建的顺序是否和执行的顺序有关系呢?还是用数据说话吧,我执行了10次,每次的输出顺序都是如此。这个引起了我的兴趣。线程2为何每次都是优先于线程1执行呢?按照cup顺序工作的原理,线程1应该先得到时间片才对啊,至少线程1和线程2应该具有同等的执行顺序才对。为何每次的结果都是线程2限制性?却是线程1先完成呢?纠结探索中,有条件的园友可以自己测试一下,看看是否有同样的问题呢。

    疑问1:同时创建线程是否线程2优先于1呢?-----单台机器实测来看貌似如此。

    疑问2:顺序创建时间差增大,执行顺序会如何?我在线程1创建后做了一个sleep(1),结果:

    thread 1 returning
    thread 1 exit code 1
    thread 2 exiting
    thread 2 exit code 2

    疑问3:顺序创建线程,线程2的执行顺序为何优于线程1?探索中...!求答案!

    环境

    vmware8.0 + windows xp + REHL6.3

  • 相关阅读:
    [bzoj 4199][NOI 2015]品酒大会
    [bzoj 5332][SDOI2018]旧试题
    「PKUWC2018」猎人杀
    「PKUWC2018」Minimax
    正规消息发送器-- ESFramework 4.0 进阶(06)
    在线用户管理--ESFramework 4.0 进阶(05)
    ESFramework 4.0 进阶(04)-- 驱动力:通信引擎(下)
    驱动力—— 通信引擎(上)—— ESFramework 4.0 进阶(03)
    核心梳理——消息处理的骨架流程——ESFramework 4.0 进阶(02)
    重登陆模式 --ESFramework 4.0 快速上手(07)
  • 原文地址:https://www.cnblogs.com/hadoopdev/p/3246070.html
Copyright © 2011-2022 走看看