多线程操作同一变量无参数版 非GIL

import threading 
from time import sleep
from datetime import datetime


date_time_format = '%y-%m-%d %H:%M:%S'

def date_time_str(date_time):
return datetime.strftime(date_time, date_time_format)

global_count = 0

def add():
global global_count
global_count = global_count + 1

def main():
print(f'---all threads start : :{date_time_str(datetime.now())}')
threads = []
n_loops = range(10)
#
for i in n_loops:
t = threading.Thread(target=add)
threads.append(t)

for i in n_loops: # start threads
threads[i].start()

for i in n_loops: # wait for all
threads[i].join() # threads to finish

print(f'---all threads finished :{date_time_str(datetime.now())}')

if __name__ == '__main__':
main()
print(global_count)

带一个参数版本 非GIL

import threading 
from time import sleep
from datetime import datetime


date_time_format = '%y-%m-%d %H:%M:%S'

def date_time_str(date_time):
return datetime.strftime(date_time, date_time_format)

global_count = 0

def add(step = 10):
global global_count
global_count = global_count + step

def main():
print(f'---all threads start : :{date_time_str(datetime.now())}')
threads = []
n_loops = range(10)
#
for i in n_loops:
t = threading.Thread(target=add,args=(i+1,))
threads.append(t)

for i in n_loops: # start threads
threads[i].start()

for i in n_loops: # wait for all
threads[i].join() # threads to finish

print(f'---all threads finished :{date_time_str(datetime.now())}')

if __name__ == '__main__':
main()
print(global_count)

加锁