程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Python threading threads share global variables in the same process

編輯:Python

One 、 Shared variable type parameters

        Variable type ( list 、 Dictionaries 、 Variable set )

        What you want to share is variable type parameters , Directly pass this parameter as an argument args Incoming thread , among sleep The function is used to reduce the running speed , It is convenient to print out the desired results

import threading
from time import sleep
def demo1(a,num):
sleep(0.5)
# by a Add elements
for i in range(num):
a.append(i)
print('demo1 Of a:{}'.format(a))
def demo2(a,num):
sleep(0.5)
# by a Add elements
for i in range(num):
a.append(i*2)
print('demo2 Of a:{}'.format(a))
def main():
# Create two parameters
a=[11,22,33]
num=8
# Create two threads , And pass two parameters to the specified function
threading.Thread(target=demo1,args=(a,num)).start()
threading.Thread(target=demo2, args=(a,num)).start()
# Number of printing threads
print(threading.enumerate())
sleep(1)
print(' Main thread a:{}'.format(a))
if __name__ =='__main__':
main()

Print the results :

You can see that the final result is that the calculations in both threads have been carried out , That is, threads in the same process share variables .

Two 、 Share immutable type parameters

          Immutable type ( Numbers 、 character string 、 Tuples 、 Immutable set )

          What you want to share is an immutable type parameter , This parameter cannot be directly passed as an argument args Incoming thread , You need to create immutable parameters before the process executes , And when you modify it in the thread, you need to declare global variables .

import threading
from time import sleep
def demo1(num):
'''a+100'''
sleep(0.5)
for i in range(num):
global a
a +=1
print('demo1 Of a:{}'.format(a))
def demo2(num):
'''a+100'''
sleep(0.5)
for i in range(num):
global a
a +=1
print('demo2 Of a:{}'.format(a))
def main():
# Create a parameter
num=100
# Create two threads , And pass the parameters to the specified function
threading.Thread(target=demo1,args=(num,)).start()
threading.Thread(target=demo2, args=(num,)).start()
# Number of printing threads
print(threading.enumerate())
sleep(1)
print(' Main thread a:{}'.format(a))
if __name__ =='__main__':
# Create parameters of immutable type
a=0
main()

Print the results :

3、 ... and 、 The mutex ( Problems encountered in the sharing process )

        When Parameters a  Add 100, Add 200 when , No problems , Add 10000000, Add twothousand ? Code up , Direct will num Change to 10000000 , The running result at this time :

         reason : There will be resource competition when multiple threads share global variables

         resolvent : Use mutexes , When a thread uses a lock , Another thread cannot operate on the object in the lock , Until unlocked , To operate the object in the lock .

import threading
from time import sleep
def demo1(num,mutex):
''' Operate on data '''
for i in range(num):
global a
# lock
mutex.acquire()
# Process the data
a +=1
# Unlock
mutex.release()
print('demo1 Of a:{}'.format(a))
def demo2(num,mutex):
''' Operate on data '''
for i in range(num):
global a
# lock
mutex.acquire()
# Process the data
a += 1
# Unlock
mutex.release()
print('demo2 Of a:{}'.format(a))
def main():
# Create a mutex , No lock by default
mutex=threading.Lock()
# Create a parameter
num=10000000
# Create two threads , And pass the parameters to the specified function
threading.Thread(target=demo1,args=(num,mutex)).start()
threading.Thread(target=demo2, args=(num,mutex)).start()
# Number of printing threads
print(threading.enumerate())
sleep(10)
print(' Main thread a:{}'.format(a))
if __name__ =='__main__':
# Create parameters of immutable type
a=0
main()

From the above, we can see that the mutex actually calls a threading Under the lock function

# Create a mutex , No lock by default
mutex=threading.Lock()
# lock
mutex.acquire()
# Process the data
a += 1
# Unlock
mutex.release()

Print the results :


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved