Multithreading-sharing global variables
From threadingImport ThreadImport Timeg_num =100def work1 (): global g_num for i in range (3): G_num + = 1 print ( "----in Work1, G_num is%d---"%g_num) def work2 (): global g_num print ( "----in Work2, G_num is%d---"%g_num) print ( "---thread was created before G_num is%d---"%g_num) T1 = thread (TARGET=WORK1) T1.start () #延时一会, make sure things in the T1 thread are done time.sleep (1) t2 = thread (TARGET=WORK2) T2.start ()
Operation Result:
is 100-------in work1, g_num is 103-------in work2, g_num is 103---
The list is passed to the thread as an argument
from threading import threadimport timedef work1 (nums): Nums.append (44) print ( "----in Work1---", nums) def work2 (nums): # Delay a while to ensure that things in the T1 thread are done time.sleep (1) print ( "----in WORK2---", nums) G_nums = [11,22,33]t1 = Thread ( Target=work1, args= (G_nums,)) T1.start () t2 = Thread (Target=work2, args= (g_nums)) T2.start ()
Operation Result:
----in work1--- [11, 22, 33, 44]----in work2--- [11, 22, 33, 44]
Summarize:
Sharing global variables across all threads within a process makes it easy to share data among multiple threads
The downside is that a thread is arbitrarily modifying a global variable that can cause confusion among multiple threads about global variables (that is, thread non-security)
==================================================================
Note: The above course notes for the study of the teachers in the classroom study notes, if necessary to reprint, if you need full notes, please contact me privately.
Featured Python Updates My study notes every day. The above content and class notes, more details to see the original link, my public number of dry goods continue to update
SOURCE Link: Article Python developer Exchange Platform
If you have better ideas and suggestions, welcome to shoot bricks together to explore. Welcome to the public number join "Python Developer Exchange Platform"
Learn Python together: multithreading-sharing global variables