Python Advanced Learning Notes (1)
threading module
threading.thread(target = (function)) is responsible for defining the child thread object
threading.enumerate() is responsible for viewing child thread objects
The test code is as follows:
import time
import threading
def sing():
for i in range(5):
print('-----Sing-----')
time.sleep(1)
def dance():
for i in range(5):
print('-----dance-----')
time.sleep(1)
def main():
t1 = threading.Thread(target=sing) #Subthread 1
t2 = threading.Thread(target=dance) #Subthread 2
t1.start()
t2.start()
while True:
print(threading.enumerate())
if len(threading.enumerate()) == 1:
break
time.sleep(1)
if __name__ == '__main__':
main()
Supplement:
Thread scheduling is random, if the main thread GG before the sub-threads, your sub-threads also GG
threading.thread() does not create a thread, it is not created until its instance.start() is called
Create threads from classes
The test code is as follows:
import threading
import time
class Person(threading.Thread):
def run(self) -> None:
for i in range(3):
print('aaa' + self.name)
time.sleep(1)
if __name__ == '__main__':
p = Person()
p.start()
for i in range(3):
print('bbb')
time.sleep(1)
Supplement:
Threading.threading is a class that declares a process by inheriting and override run functions
Multithreaded Sharing Global Variables
The test code is as follows:
import threading
import time
num = 100
def test1():
global num
num += 1
print(num)
def test2():
print(num)
def main():
t1 = threading.Thread(target=test1)
t2 = threading.Thread(target=test2)
t1.start()
time.sleep(1)
test2()
if __name__ == '__main__':
main()
If creating a thread requires parameters, use args
The test code is as follows:
num = [1,1,2,3]
def test1(args):
args.append('hhs')
print(args)
def main():
t1 = threading.Thread(target=test1,args=(num,))
t1.start()
print(num)
if __name__ == '__main__':
main()
Plus: args is followed by a tuple, missing commas will cause errors
Problems with multithreaded sharing of global variables
The test code is as follows:
import threading
import time
g_num = 0
def count1(n):
global g_num
for i in range(n):
g_num += 1
def count2(n):
global g_num
for i in range(n):
g_num += 1
def main():
t1 =threading.Thread(target=count1,args=(100000,))
t2 = threading.Thread(target=count2, args=(100000,))
t1.start()
t2.start()
time.sleep(2)
print('normal num For 2000, Actual num by%d' % g_num)
if __name__ == '__main__':
main()
Supplement: The output is 175586, which is different from the normal result
Resolve the problem:
1.cpu is executed sentence by sentence
2. If you parse g_num += 1 into many sentences, if thread 1 only executes 1-2 sentences and the third sentence has not been assigned back, then thread 2 is called, and the result of the addition is not equal to the expected result