###### tags: `python` `threading` # Threading ## solve problems >[file name ≠ threading](https://stackoverflow.com/questions/41012121/attributeerror-module-object-has-no-attribute-rlock) ![](https://i.imgur.com/36dggJM.png) ## Added a job ```python= import threading def threadJob(): print("this job displays current thread, number is %s" %threading.currentThread()) def main(): addedThread=threading.Thread(target=threadJob) addedThread.start() # to tell us how many threading print(threading.activeCount()) # to tell us threading name print(threading.enumerate()) #enumerate 列舉 # to tell us currently execute threads print(threading.currentThread()) if __name__ == '__main__': main() ``` ## join() to control threading executed sequence ```python= import threading import time def thread1(): print("T1 start\n") for i in [3,2,1]: print(i) time.sleep(1) print("T1 all down\n") def thread2(): print("T2 start\n") for i in [5,4,3,2,1]: print(i) time.sleep(1) print("T2 all down\n") def main(): addedThread1=threading.Thread(target=thread1,name="T1") addedThread2=threading.Thread(target=thread2,name="T2") addedThread1.start() addedThread2.start() addedThread1.join() # join, it will wait for the subthread to execute completely and it will execute follow programs addedThread2.join() print("main finished\n") if __name__ == '__main__': main() ``` >join() It will wait for the subthread to execute completely and it will execute follow programs ## mult-threading computing ```python= import threading from queue import Queue import time list =[[1,2,3,4],[4,5,6,7],[8,9,10,11],[12,12,12,12]] def job(list,q): for i in range(len(list)): list[i] = list[i]**2 time.sleep(1) print(f'through compute time is {i}') q.put(list) def multithreading(): q=Queue() threads=[] for i in range(4): thread=threading.Thread(target=job,args=(list[i],q)) thread.start() threads.append(thread) for thread in threads: threads =thread.join() result=[] for i in range(4): result.append(q.get()) print(result) print("We didn't wait 12 seconds to complete computing if we use multi-threding to compute") if __name__ =="__main__": multithreading() ``` >Remark: >In multi-threading didn't return values >So, we use Queue instead of the return