This article is based on 【 Don't worry about it Python】Threading Learn to multithread Python Video of learning records .
Don't worry about it Python So handsome and cute hahaha .
import threading
def thread_job():
print('This is an added Thread, number id %s' % threading.current_thread())
def main():
added_thread = threading.Thread(target=thread_job) # Create thread
added_thread.start() # Start thread
if __name__ == '__main__':
main()
First think about a few questions :
import threading
import time
def thread_job():
print('T1 start')
for i in range(10):
time.sleep(0.1)
print('T1 finish')
def t2_job():
print('T2 start')
print('T2 finish')
def main():
added_thread = threading.Thread(target=thread_job, name='T1')
thread2 = threading.Thread(target=t2_job)
added_thread.start()
thread2.start()
added_thread.join()
thread2.join()
print('all down!')
if __name__ == '__main__':
main()
You can pass parameters to the thread , But the thread cannot have a return value .
The purpose of the following example is to data All values in the list are squared :
import threading
import time
from queue import Queue
# List data to be modified
data = [[1, 2, 3], [3, 4, 5], [4, 4, 4], [5, 5, 5]]
# Define a function , Square the values in the list
def job(l):
for i in range(len(l)):
l[i] = l[i]**2
return l
# If you don't use multithreading , This can be achieved in the following ways
def no_threading():
result = []
for d in data:
r = job(d)
result.append(r)
print(result)
def job2(l, q):
for i in range(len(l)):
l[i] = l[i]**2
q.put(l)
def multithreading():
q = Queue()
threads = []
# Start thread
for i in range(4):
t = threading.Thread(target=job2, args=(data[i], q))
t.start()
threads.append(t)
# Recycle thread
for thread in threads:
thread.join()
# get data
results = []
for _ in range(4):
results.append(q.get())
print(results)
if __name__ == '__main__':
# no_threading()
multithreading()
import threading
def job1():
global A, lock
lock.acquire()
for i in range(10):
A += 1
print('job1', A)
lock.release()
def job2():
global A, lock
lock.acquire()
for i in range(10):
A += 10
print('job2', A)
lock.release()
if __name__ == '__main__':
A = 0
lock = threading.Lock()
t1 = threading.Thread(target=job1)
t2 = threading.Thread(target=job2)
t1.start()
t2.start()
t1.join()
t2.join()