• apple平台下的objc的GCD,多线程编程就是优雅自然。


    在apple的操作系统平台里,GCD使得多线程编程是那么的优雅自然。
    在传统的多线程编程中,首先要写线程处理循环;之后还有事件队列,消息队列;还要在线程循环中分离事件解释消息,分派处理;还要考虑线程间是否要同步;还要写许多有着可能费解的函数名的回调处理程序,注册回调程序,而且代码分散即使同一文件也不容易看出与哪些线程对应或者彼此间的是否有次序或并发的关系,不利于调试;另外还要考虑是否需要使用线程池,线程线使用何种模式等。
    在apple平台的objc中,只需要如下:

    A* a;
    dispatch_async(queue_serial, ^{
        // handle a in step 1;
        dispatch_async(queue_concurrent, ^{
            // handle a in step 2;
            dispatch_async(queue_main, ^{
                // handle a in step 3;
            });
        });
    });

    优雅,至少我是这样以为的。一目了然,整个流程分了三个子流程,分别在不同线程中运行。子流程间可以并发,第二个子流程可以并行,各个子流程在哪个线程中执行(,除了queue_main和queue_backgroup,其余都是工作线程),所写即所想。
    传统中多线程编程的影子无踪,只知道我写到这里要用到多程线异步执行我的任务,好就我说一声异步执行。

    并不是说多线程编程就只有这么些,只不过在传统中多线程编程中,实现上面的代码,还得费不少功夫的。不假思索写下的伪代码都有下面这么多,还不好理解。

    struct Thread
    {
        void putq(msg);
        uint createThread();
    };
    
    struct ThreadStep1 : public Thread
    {
        queue q;
        void register(handler);
        void run() { 
            wait(q);
            msg = getq(q);
            handler = findHandler(msg);
            handler(msg);
        } 
    };
    
    struct ThreadStep2 : public Thread
    {
        static queue q;
        static void register(handler);
        void run() { 
            wait(ThreadStep2::q);
            msg = getq(ThreadStep2::q);
            handler = findHandler(msg);
            handler(msg);
        } 
    };
    
    struct ThreadStep2Pool
    {
        ThreadStep2 threads[n];
        void createThreads();
        void register(handler);
    };
    
    struct ThreadStep3 : public Thread
    {
        queue q;
        void register(handler);
        void run() { 
            wait(q);
            msg = getq(q);
            handler = findHandler(msg);
            handler(msg);
        } 
    };
    
    void handler1(void* ctx)
    {
      // handle get_a(ctx) in step 1
      get_p2(ctx)->putq(ctx);
    }
    void handler2(void* ctx)
    {
      // handle get_a(ctx) in step 2
      get_t3(ctx)->putq(ctx);
    }
    void handler3(void* ctx)
    {
      // handle get_a(ctx) in Step 3
    }
    main()
    {
        ThreadStep1 t1;
        ThreadStep2Pool p2;
        ThreadStep3 t3;
        
        t1.createThread();
        p2.createThreads();
    
        t1.register(handler1);
        p2.register(handler2);
        t3.register(handler3);
        
        A* a = new a;
        msg msg(a, t1, p2, t3);
        t1.putq(msg);
    
        t3.run();
    }
  • 相关阅读:
    如何避免delete和delete[]的尴尬?
    笔面集锦:判断单链表里面是否有环及相关扩展题(转)
    各排序算法的C++实现与性能测试(转)
    五个好的C语言编程实践
    Reviewboard管理员指南(5.5)—— Permission Groups(重要)
    Jenkins CLI getjob与RoleBased Strategy的那点事
    Reviewboard管理员指南(5.4)—— Default Reviewers(重要)
    Reviewboard管理员指南(4.2)—— Administrator Dashboard
    Maven Nexus admin密码重置的方法
    Reviewboard管理员指南(5.2)—— Access Control(重要)
  • 原文地址:https://www.cnblogs.com/bbqzsl/p/5132196.html
Copyright © 2020-2023  润新知