• Operating System: Three Easy Pieces ---An Example: Thread Creation (Note)


    Let's say we wanted to run a program that created two threads, each of which was doing

    some independently work, in this case printing "A" or "B". The code is shown in Figure 26.2.

    The main program creates two threads, each of which will run the function mythread(), 

    though with different arguments (the string A or B). Once a thread is created, it may start

    running right away (depending on the whims of scheduler); alternatively, it may be put in a

    "ready" but not "running" state and thus not run yet. After creating the two threads (T1 and

    T2), the main thread calls pthread_join(), which waits for a particular thread to complete.

     Let us examine the possible execution ordering of this little program. In the execution diagram,

    time increases in the downwards direction, and each column shows when a different thread

    (the main one, or Thread 1, or Thread 2) is running.

    Note, however, that this oedering is not the only possible ordering. In face, given a sequence

    of instructions, there are quite a few, depending on which thread the scheduler decides to run

    at agiven point. For example, once a thread is created, it may run immediately, which would

    lead to the execution shown in Figure 26.4.

    We also could even see "B" printed before "A", if, say, the scheduler decided to run Thread 2

    first even though Thread 1 was created earlier; there is no reason to assume that a thread 

    that is created first will run first. Figure 26.5 shows this final execution ordering, with Thread

    2 getting to strut its stuff before Thread 1.

    As you might be able to see, one way to think about thread creation is that it is a bit like 

    making a function call; however, instead of first executing the function and then returning 

    to the caller, the system instead creates a new thread of executing for the routine that is

    being called, and it runs independently of the caller, perhaps before returning from the

    create, but perhaps much later.

    As you also might be able to tell from this example, threads make life complicated; it is

    already hard to tell what will run when! Computeres are hard enough to understand without

    concurrency. Unfornately, with concurrency, it gets worse. Much worse.

  • 相关阅读:
    用Java实现四则运算
    敏捷开发角色分配
    需求分析之WBS
    需求分析之NABCD
    电梯演说
    开发流程的选择
    软件团队模式的选择
    维护日程管理项目
    日程管理系统中找错误
    Android的测试
  • 原文地址:https://www.cnblogs.com/miaoyong/p/4939229.html
Copyright © 2020-2023  润新知