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.

  • 相关阅读:
    Serverless 的初心、现状和未来
    父亲的茶杯
    子慕谈设计模式系列(三)
    子慕谈设计模式系列(二)——设计模式六大原则
    子慕谈设计模式系列(一)
    初入angular4——实际项目搭建总结
    欲练JS,必先攻CSS——前端修行之路
    运用google-protobuf的IM消息应用开发(前端篇)
    “倔驴”一个h5小游戏的实现和思考(码易直播)——总结与整理
    【猿分享第10期】微信小程序Meetup扫盲专场回顾(转载)
  • 原文地址:https://www.cnblogs.com/miaoyong/p/4939229.html
Copyright © 2011-2022 走看看