PROGRAMMING

  MINTE9
REMEMBERS




Threads

p400 ! A multithreaded program is like having multip many fingers.
 
"""Threads:
When you use time.sleep() your program cannot do anything else,
unless you use threads.
A single-thread program is like placing one finger on a line of code,
then moving to the next.
A multi-threaded program has multiple "fingers"
"""
import threading, time

def pause():
    time.sleep(5)
    print('Wake up! ' + threading.currentThread().name)

print('Program start') # main

A = threading.Thread(target=pause) # second
A.start()
B = threading.Thread(target=pause, name='B') # third
B.start()

print('Program end') # main

# Program start
# Program end
# Wake up! Thread-1
# Wake up! B

Arguments

p402 You can pass target function's arguments.
 
"""Thread function's arguments
When target function you want to call to run in a thread 
has arguments.
"""
import threading, time

def pause(seconds):
    i = 0
    while i < seconds:
        print('Run thread: ' + threading.currentThread().name)
        i = i + 1
        time.sleep(1)

print('Start main')
threading.Thread(target=pause, name='B', args=[5]).start()
print('End main')

# Start main
# Run thread: B
# End main
# Run thread: B
# Run thread: B
# Run thread: B
# Run thread: B

Concurrency

! To avoid concurrency issues, never let threads change the same variable.
 
"""Threads Concurrency:
When you create a new thread make sure its target function
uses only local variable in that function.
"""
import threading, time


"""Incorrect"""
i = 0
def pause():
    global i # Look Here
    while i < 3:
        print('Run thread: ' + threading.currentThread().name)
        i = i + 1
        time.sleep(1)

print('Start')
threading.Thread(target=pause, name='A').start()
threading.Thread(target=pause, name='B').start()
print('End')
    # Start
    # Run thread: A
    # Run thread: B
    # End
    # Run thread: A

time.sleep(3)
print()


"""Correct"""
def pauseC():
    i = 0
    while i < 3:
        print('Run thread: ' + threading.currentThread().name)
        i = i + 1
        time.sleep(1)

print('Start')
threading.Thread(target=pauseC, name='A2').start()
threading.Thread(target=pauseC, name='B2').start()
print('End')
    # Start
    # Run thread: A2
    # Run thread: B2
    # End
    # Run thread: A2
    # Run thread: B2
    # Run thread: A2
    # Run thread: B2

Questions     github Scheduler
Subprocess
        A B C D E F
🔔
1/2