Implementation of "Python" multi-threaded shared variables

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.