zoukankan      html  css  js  c++  java
  • 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.

  • 相关阅读:
    添加事件(jquery)
    闭包导致的问题
    学习之js绑定事件
    第二条 一个类如果有多个参数,考虑用Builder构造者模式
    用Intellij IDEA 创建第一个maven项目!
    OrderSessionHelper查看订单在session是否存在的辅助类
    css——overflow
    css——盒子
    css——外部样式
    css——权重叠加
  • 原文地址:https://www.cnblogs.com/miaoyong/p/4939229.html
Copyright © 2011-2022 走看看