1.g_num is not a global variable
fromThreadingImportThreadImport Timedeftest1 (): G_num= 100G_num+ = 1Print("---1test1--g_num=%d"%g_num) Time.sleep (2)deftest2 (): Time.sleep (1) Print("---2test2--g_num=%d"%g_num) T1= Thread (target=test1) T1.start () T2= Thread (target=test2) T2.start ()
## # Results---1test1--g_num=101ExceptioninchThread Thread-2: Traceback (most recent): File"/usr/lib/python3.5/threading.py", line 914,inch_bootstrap_inner self.run () File"/usr/lib/python3.5/threading.py", Line 862,inchRun Self._target (*self._args, * *Self._kwargs) File"10-multithreading-non-shared data. PY", Line 12,inchtest2Print("---2test2--g_num=%d"%g_num) Nameerror:name'G_num' is notDefined
2. Thread Name
Import Threadingin [2]: Threading.current_thread () out[2]: <_mainthread (Mainthread, started 139965328148224) > in[3]: Threading.current_thread (). nameout['mainthread '
3. Two threads executing the same function
- Two threads do not have a relationship with the function
- Function The individual is personal, the variables inside the function are not related
fromThreadingImportThreadImportThreadingImport Timedeftest1 (): Name=Threading.current_thread (). NamePrint("---The thread is%s--"%name) G_num= 100ifName = ="Thread-1": G_num+ = 1Print("---%s--g_num=%d"%(name,g_num))Else: Time.sleep (2) Print("----%s--g_num=%d"%(name,g_num)) T1= Thread (target=test1) T1.start () T2= Thread (target=test1) T2.start ()
Small summary
- In multithreaded development, global variables are data shared by multiple threads, while local variables, such as their own, are non-shared
9 multi-threaded to unshared data