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.

  • 相关阅读:
    UEditor用法
    String,StringBuffer与StringBuilder差异??
    TsFltMgr.sys其原因是,该系统蓝屏QQ计算机管理器!
    Linux编程实现守护进程
    开机黑屏 只显示鼠标 电脑黑屏 有只老鼠 举 [我们已经成功地解决了]
    页面背景图像的代码
    动态规划01背包问题
    关键部分CCriticalSection使用
    编程:获取股票实时行情数据大全
    iphone开发教程下载
  • 原文地址:https://www.cnblogs.com/miaoyong/p/4939229.html
Copyright © 2011-2022 走看看