按这个测试了,结果有点疑问

按这个测试了,结果有点疑问

# 具体遇到的问题
为什么user.json中不是20个,总会少几个。。。
# 报错信息的截图

# 相关课程内容截图
http://img1.sycdn.imooc.com//climg/5fbe752b09bf079e14190429.jpg

# 尝试过的解决思路和结果

# 粘贴全部相关代码,切记添加代码注释(请勿截图)

在这里输入代码,可通过选择【代码语言】突出显示

正在回答 回答被采纳积分+1

登陆购买课程后可参与讨论,去登陆

2回答
好帮手慕小轩 2020-11-26 17:15:25

同学,你好!使用多进程执行,结果显示不全,可能是电脑cup的问题,同学可以使用多线程执行,可参考下面代码示例:

​# coding:utf-8
import multiprocessing
import os
import threading
import time
import json

from common.utils import check_file, timestamp_to_string
from common.error import (UserExistsError, RoleError,
LevelError, NegativeNumberError,
CountError)
from common.consts import ROLES, FIRSTLEVELS, SECONDLEVELS


class Base(object):
def __init__(self, user_json, gift_json):
self.max_gift_counts = 3
# manger = multiprocessing.Manager()
# self.lock = manger.Lock()
self.lock = threading.Lock()
self.user_json = user_json
self.gift_json = gift_json

def __read_users(self, time_to_str=False):
with open(self.user_json, 'r') as f:
data = json.loads(f.read())

if time_to_str == True:
for username, v in data.items():
v['create_time'] = timestamp_to_string(v['create_time'])
v['update_time'] = timestamp_to_string(v['update_time'])
data[username] = v
return data

def write_user(self, **user): # password active
if 'username' not in user:
raise ValueError('missing username')
if 'role' not in user:
raise ValueError('missing role')

user['active'] = True
user['create_time'] = time.time()
user['update_time'] = time.time()
user['gifts'] = []

users = self.__read_users()

if user['username'] in users:
raise UserExistsError('username %s had exists' % user['username'])

users.update(
{user['username']: user}
)
self.__save(users, self.user_json)

def __save(self, data, path):
json_data = json.dumps(data)
self.lock.acquire()
try:
with open(path, 'w') as f:
f.write(json_data)
finally:
self.lock.release()


if __name__ == '__main__':
gift_path = os.path.join(os.getcwd(), 'storage', 'gift.json')
user_path = os.path.join(os.getcwd(), 'storage', 'user.json')
print(gift_path)
print(user_path)
# pool = multiprocessing.Pool(3)
# manger = multiprocessing.Manager()
# lock = manger.Lock()
base = Base(user_json=user_path, gift_json=gift_path)
for i in range(20):
t = threading.Thread(target=base.write_user, kwargs={'username': f'd{i}', 'role': 'admin'})
t.start()
t.join()


  • 提问者 慕码人9577935 #1

    ?我改成线程池又没反应了

    http://img1.sycdn.imooc.com//climg/5fbf851d092d878a06470538.jpg


    2020-11-26 18:45:33
  • 好帮手慕小轩 回复 提问者 慕码人9577935 #2

    ​同学,你好!之所以没有结果,是因为传参数的时候user值不对,没有获取到值,可print(user)进行查看,键是kwargs,通过user['kwargs']键获取字典里面的值

     http://img1.sycdn.imooc.com//climg/5fbf93d7090679a507160079.jpghttp://img1.sycdn.imooc.com//climg/5fbf93f4092e94fa07100068.jpg

    def write_user(self, **user):  # password active
    user = user['kwargs']
    if 'username' not in user:
    raise ValueError('missing username')
    if 'role' not in user:
    raise ValueError('missing role')

    user['active'] = True
    user['create_time'] = time.time()
    user['update_time'] = time.time()
    user['gifts'] = []

    users = self.__read_users()

    if user['username'] in users:
    raise UserExistsError('username %s had exists' % user['username'])

    users.update(
    {user['username']: user}
    )
    self.__save(users, self.user_json)


    2020-11-26 20:14:08
  • 提问者 慕码人9577935 #3

    我发现我只要建了池的都会有问题,只写多线程或者多进程结果就没问题

    2020-11-26 22:10:32
好帮手慕小轩 2020-11-26 11:27:12

同学,你好!测试结果少,跟多进程写入文件有关,要在初始化的时候创建锁,可参考下面代码示例:
http://img1.sycdn.imooc.com//climg/5fbf1dbf09f1262006770237.jpg
http://img1.sycdn.imooc.com//climg/5fbf1ed80950cd6e05210358.jpg
http://img1.sycdn.imooc.com//climg/5fbf1e3f09708d6b15980535.jpg

  • 提问者 慕码人9577935 #1
    试了一下,还是少结果,range5个好像可以,20个就不行了
    2020-11-26 14:17:12
问题已解决,确定采纳
还有疑问,暂不采纳

恭喜解决一个难题,获得1积分~

来为老师/同学的回答评分吧

0 星
请稍等 ...
意见反馈 帮助中心 APP下载
官方微信

在线咨询

领取优惠

免费试听

领取大纲

扫描二维码,添加
你的专属老师