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)
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)
thread.start()
print('Main end -', threading.currentThread().name)
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)
thread = threading.Thread(target=pause_task, name='Second-Thread', args=['myfile'])
thread.start()
print('Main end -', threading.currentThread().name)
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
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')
myVar = 'A'
def correct_local_variable_task():
time.sleep(1)
myVar = threading.currentThread().name
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')