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.
posted on 2015-11-05 13:32 Persistence 阅读(123) 评论(0) 编辑 收藏 举报