yield() - causes the calling thread to temporarily give up execution to allow other threads
to compete for CPU resources.
thread A | thread B |
i = 0
while(T) {
i = i + 1
cat("Thread A",i, "\n")
yield()
}
|
i = 0
while(T) {
i = i + 1
cat("Thread B",i, "\n")
yield()
}
|
|---|
yield() command and the output will be something like
Thread A 1 Thread B 1 Thread A 2 Thread B 2 Thread A 3 Thread B 3 ... ...Without the yield, we might see runs of one thread, such as
Thread A 1 Thread A 2 Thread A 3 Thread B 1 Thread A 4 Thread B 2 ... ...