Python 3 | Threading works weirdly -


i'm learning python 3 , watched tutorial threading:

https://www.youtube.com/watch?v=waxk8g1hb_q&index=33&list=pl6gx4cwl9dgacbmi1sh6oamk4jhw91mc_#t=365.299172

i tested example code reason result sort of weird.

import threading  class messenger(threading.thread):     def run(self):         _ in range(10):             print(threading.currentthread().getname())   m1 = messenger(name="send messages") m2 = messenger(name="receive messages") m1.start() m2.start() 

i expecting program print out "send messages" , "receive messages" on sort of random order, happened, , i'm not quite sure why:

send messagesreceive messages  send messagesreceive messages  send messagesreceive messages  send messagesreceive messages  send messagesreceive messages  send messagesreceive messages  send messagesreceive messages  send messagesreceive messages  send messagesreceive messages  send messagesreceive messages 

can explain me why results printed way? given!

i ended getting different results when ran code snippet. situation happening cpu scheduling threads in "correct" order on run posted, produce different results if continue run multiple times. normal threading behavior, because cpu decides when each process gets run.

i make sure running exact code posted, because output separated new line characters while yours seems not be.

send messages send messages receive messages send messages send messages send messages send messages receive messages receive messages send messages receive messages send messages receive messages send messages receive messages send messages receive messages receive messages receive messages receive messages 

running code:

import threading  class messenger(threading.thread):     def run(self):         _ in range(10):             print(threading.currentthread().getname())   m1 = messenger(name="send messages") m2 = messenger(name="receive messages") m1.start() m2.start() 

if read more:

https://www.cs.uic.edu/~jbell/coursenotes/operatingsystems/5_cpu_scheduling.html

the important part section on cpu scheduler:

  • whenever cpu becomes idle, job of cpu scheduler ( a.k.a. short-term scheduler ) select process ready queue run next.

  • the storage structure ready queue , algorithm used to
    select next process not fifo queue. there are
    several alternatives choose from, numerous adjustable
    parameters each algorithm, basic subject of this
    entire chapter.


Comments

Popular posts from this blog

ios - RestKit 0.20 — CoreData: error: Failed to call designated initializer on NSManagedObject class (again) -

java - Digest auth with Spring Security using javaconfig -

laravel - PDOException in Connector.php line 55: SQLSTATE[HY000] [1045] Access denied for user 'root'@'localhost' (using password: YES) -