Brief introduction:
For Python2, for a global variable, you do not need to declare global if you use only its value in your function, and you do not assign a value to it (meaning a = xxx).
Conversely, if you assign a value to it, then you need to declare global.
Declaring global means that you are assigning a value to a global variable instead of assigning a value to a local variable.
If multiple threads or processes simultaneously manipulate this variable may lead to preemption of resources, variables can not operate according to the predetermined logic, at this time, before changing variables need to add a mutex to the variable, the operation is completed after releasing the mutex.
Off Topic:
GIL (Global interpreter Lock), which causes only one thread to use the interpreter at any one time, when used for IO-intensive tasks, the thread releases the interpreter during IO.
Multi-Threading is not recommended in CPU-heavy tasks, and multithreading is recommended in non-CPU busy tasks.
By the way, the benefits of using multiple processes: Full parallelism, no GIL restrictions, and full use of multi-CPU multicore environments.
Multi-threaded using Mutex lock Demo:
" multithreading global variables use mutex key: Declare a global mutex" ' Import threadingimport timecounter = 0mutex = Threading. Lock () class MyThread (threading. Thread): def __init__ (self): threading. Thread.__init__ (self) def run (self): Global Counter, Mutex time.sleep (1); If Mutex.acquire (): counter + = 1 print "I am%s, set counter:%s"% (self.name, counter) mutex.release () If _ _name__ = = "__main__": for I in range (0): my_thread = MyThread () My_thread.start ()
Implementation of "Python" multi-threaded shared variables