minte9
LearnRemember





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.
 
def pause_task():
    time.sleep(1)
    print(threading.currentThread().name)

if __name__ == '__main__':
    print('Main start -', threading.currentThread().name)

    # Start new threads
    thread = threading.Thread(target=pause_task, name='Second-Thread')
    thread.start()

    thread = threading.Thread(target=pause_task, name='Third-Thread')
    thread.start()

    thread = threading.Thread(target=pause_task) # default name
    thread.start()

    print('Main end -', threading.currentThread().name)

"""
    Main start - MainThread
    Main end - MainThread
    Second-Thread
    Third-Thread
    Thread-20
"""

Arguments

You can pass target function's arguments.
 
import threading, time

def pause_task(file):
    time.sleep(1)
    print(f"File = {file} -", threading.currentThread().name)

if __name__ == '__main__':
    print('Main start -', threading.currentThread().name)

    # Start new thread
    thread = threading.Thread(target=pause_task, name='Second-Thread', args=['myfile'])
    thread.start()
    
    print('Main end -', threading.currentThread().name)

"""
    Main start - MainThread
    Main end - MainThread
    File = myfile - Second-Thread
"""

Concurrency

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

name = 'A'
def incorrect_global_variable_task():
    time.sleep(1)

    global name # Look Here
    print('Thread: ' + name)
    name = threading.currentThread().name

print('Start')
threading.Thread(target=incorrect_global_variable_task, name='A').start()
threading.Thread(target=incorrect_global_variable_task, name='B').start()
print('End')

"""
    Start
    End
    Thread: A
    Thread: A
"""
 
myVar = 'A'
def correct_local_variable_task():
    time.sleep(1)

    myVar = threading.currentThread().name # local variable
    print('Thread: ' + myVar)

print('Start')
threading.Thread(target=incorrect_global_variable_task, name='A').start()
threading.Thread(target=incorrect_global_variable_task, name='B').start()
print('End')

"""
    Start
    End
    Thread: B
    Thread: A
"""



  Last update: 294 days ago