python 全局列表_多线程在python中修改全局列表

i want to add an item into a global list every 2 seconds in one thread,

and save the list into database before empty it every 3 seconds in another thread.

i create two local varibles to monitor the total added items and total saveditems, they should be equal every 6 senconds,but it is not.

here is my code:

import datetime

import psutil,os,time

from threading import *

class AddToList(Thread):

totalAdded=0

def run(self):

lock=RLock()

lock.acquire()

while True:

entryList.append("AddToList at "+str(datetime.datetime.now()))

self.totalAdded=self.totalAdded+len(entryList)

print("totalAdded:"+str(self.totalAdded))

time.sleep(2)

lock.release()

class SaveList(Thread):

totalSaved=0

'''save entry to server'''

def __init__(self):

Thread.__init__(self)

def run(self):

lock=RLock()

lock.acquire()

while True:

#save list to database,then empty the list

self.totalSaved=self.totalSaved+len(entryList)

del entryList[:]

print("totalSaved:"+str(self.totalSaved))

time.sleep(3)

lock.release()

if __name__=="__main__":

global entryList

entryList=[]

addClass= AddToList()

addClass.start()

saveClass=SaveList()

saveClass.start()

result:

totalAdded:2

totalSaved:2

totalAdded:3

totalSaved:3totalAdded:4

totalAdded:6

totalSaved:5

totalAdded:7

totalSaved:6

totalAdded:8

totalAdded:10

totalSaved:8

totalAdded:11

totalSaved:9

totalAdded:12

totalAdded:14

totalSaved:11

totalAdded:15

totalSaved:12

...........

...........

totalAdded:51

totalSaved:39totalAdded:52

totalAdded:54

totalSaved:41

totalAdded:55

totalSaved:42

totalAdded:56

totalAdded:58

totalSaved:44

totalAdded:59

totalSaved:45totalAdded:60

......

......

i anm new to python and searched a lot about threading ,Lock and RLock ,but with no luck.

where am wrong?

解决方案

To make Lock and RLock work you must use the same object in every thread. The lock objects must have the same "visibility" of the object that you want to "protect".

Here is a new version of you code which should work. It also avoid using things like global variables etc.

import datetime

import time

import threading

class AddToList(threading.Thread):

def __init__(self, lock, entryList):

threading.Thread.__init__(self)

self.totalAdded = 0

self.entryList = entryList

self.lock = lock

def run(self):

while True:

self.lock.acquire()

entryList.append("AddToList at {}".format(datetime.datetime.now()))

self.totalAdded += 1

self.lock.release()

print("totalAdded: {}".format(self.totalAdded))

time.sleep(2)

class SaveList(threading.Thread):

def __init__(self, lock, entryList):

threading.Thread.__init__(self)

self.totalSaved = 0

self.entryList = entryList

self.lock = lock

def run(self):

while True:

self.lock.acquire()

self.totalSaved += len(self.entryList)

del self.entryList[:]

self.lock.release()

print("totalSaved: {}".format(self.totalSaved))

time.sleep(3)

if __name__=="__main__":

lock=threading.Lock()

entryList=[]

addClass = AddToList(lock, entryList)

addClass.start()

saveClass = SaveList(lock, entryList)

saveClass.start()

Some things to note:

Use Lock instead of RLock when you don't have any particular needs. RLock is much slower.

As already pointed out by someone it is better avoid using global variables when not needed. Also Class variables should be used only when it makes sense.

When you use a lock you should try to limit as much as possible the code between acquire and release. In you previous code you never release the lock.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值