Python multitasking programming - sharing variables between threads

Related Tags:1.Empower Your Web with Python
2. Shodan and Python API

Problem: Error sharing global variable data between threads



import threading

g_num = 0


def task1 ():
for i in range ( 1000000 ):
global g_num
g_num += 1
print ( 'TASK1:' , g_num )

def task2 ():
for i in range ( 1000000 ):
global g_num
g_num += 1
print ( 'TASK2:' , g_num )


if __name__ == "__main__" :
first = threading.Thread ( target = task1 ) _ _
second = threading.Thread ( target = task2 ) _ _
first.start ( ) _
second.start ( ) _


operation result:




Theoretically, 1 million loops are implemented, and 1 is added to the global variable every time the loop is executed, and the final result should be 2,000,000. The actual result is shown above.

reason:



Two threads operate on global variables at the same time. When thread 1 reads the global variable, thread 2 also reads the global variable. When performing an operation on a variable, the original variable is read, not the variable after the operation. Because thread 1 did not commit after the operation on the variable, thread 2 also read the previous variable value.
Solution

Use process synchronization to ensure that only one thread operates on data at a time.

1. Use the join() method

import threading

g_num = 0


def task1 ():
for i in range ( 1000000 ):
global g_num
g_num += 1
print ( 'TASK1:' , g_num )

def task2 ():
for i in range ( 1000000 ):
global g_num
g_num += 1
print ( 'TASK2:' , g_num )


if __name__ == "__main__" :
first = threading.Thread ( target = task1 ) _ _
second = threading.Thread ( target = task2 ) _ _
first.start ( ) _
first.join ( ) _
second.start ( ) _
Results of the:



Principle: The first.join() thread is added to wait when the program is running, and the second thread will start to run after the first thread is completed, ensuring that only one thread operates on the variable at the same time.
Thread synchronization: After one task is executed, another task can be executed, and only one task is executing at the same time.

2. Mutex

import threading

g_num = 0

# Creating a mutex is essentially a function via
LOCK = threading.Lock ( ) _
def task1 ():
# lock
LOCK.acquire ( ) _
for i in range ( 1000000 ):
global g_num
g_num += 1
print ( 'TASK1:' , g_num )
# release lock
LOCK.release ( ) _


def task2 ():
LOCK.acquire ( ) _
for i in range ( 1000000 ):
global g_num
g_num += 1
print ( 'TASK2:' , g_num )
LOCK.release ( ) _


if __name__ == "__main__" :
first = threading.Thread ( target = task1 ) _ _
second = threading.Thread ( target = task2 ) _ _
first.start ( ) _
second.start ( ) _

Results:





Principle: For shared data locking, only one thread operates at the same time, and multiple threads grab it together, and the lock function in threading is used first to grab it. When running the first thread, first lock the current thread with lock.acquire(), during which other threads cannot run. When the loop ends, use lock.release() to release the current thread thread, after which other threads can operate. Make sure that only the same thread is going on at the same time.
However, mutex locks affect the efficiency of the code to a certain extent, turning multitasking into single-task execution, and may also cause deadlock problems (caused by the lack of timely release of locks).

Copyright statement: The content of this article is contributed by Alibaba Cloud's real-name registered users. The copyright belongs to the original author. The Alibaba Cloud developer community does not own the copyright and does not assume the corresponding legal responsibility. For specific rules, please refer to the " Alibaba Cloud Developer Community User Service Agreement " and " Alibaba Cloud Developer Community Intellectual Property Protection Guidelines ". If you find any content suspected of plagiarism in this community, fill out the infringement complaint form to report it. Once verified, this community will delete the allegedly infringing content immediately.

Related Articles

Explore More Special Offers

  1. Short Message Service(SMS) & Mail Service

    50,000 email package starts as low as USD 1.99, 120 short messages start at only USD 1.00

phone Contact Us