为啥线程数不同,秒杀结果不同,好想知道这个具体原理啊.麻烦老师解答一下.具体看以下代码和截图
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 | import redis import random from concurrent.futures import ThreadPoolExecutor # 模拟抢购 pool = redis.ConnectionPool(host = 'localhost' , port = 6379 , password = 123 , db = 0 , max_connections = 20 ) con = redis.Redis(connection_pool = pool) con_buy = redis.Redis(connection_pool = pool) # Python 线程池 executor = ThreadPoolExecutor( 200 ) def get_user_id(): """ 创建user id 的集合""" s = set () while True : if len (s) = = 1000 : break num = random.randint( 100000 , 999999 ) s.add(num) return s def buy(): """ 模拟购买场景 """ try : pipline = con_buy.pipeline() if con_buy.exists( 'kill_flag' ) = = 1 : pipline.watch( 'kill_flag' , 'kill_user' ) total = int (pipline.get( 'kill_total' ).decode( 'utf-8' )) # print(total) num = int (pipline.get( 'kill_num' ).decode( 'utf-8' )) # print(num) if num < total: pipline.multi() pipline.incr( 'kill_num' ) s = get_user_id() user_id = s.pop() pipline.rpush( 'kill_user' , user_id) pipline.execute() print ( '第{0}个秒杀成功,总共有{1},还有{2}个' . format (num + 1 , total, total - num - 1 )) # except Exception as e: # print(e) finally : pipline.reset() def main(): try : con.delete( 'kill_total' , 'kill_num' , 'kill_flag' , 'kill_user' ) con. set ( 'kill_total' , 50 ) con. set ( 'kill_num' , 0 ) con. set ( 'kill_flag' , 1 ) con.expire( 'kill_flag' , 600 ) for i in range ( 1000 ): executor.submit(buy) print ( "秒杀结束" ) except Exception as e: print (e) # finally: # # del con # del con_buy if __name__ = = '__main__' : main() |
我之前用200个线程总是抢不完, 换了线程总数,终于可以了,然后就测试了一下,发现,不同的线程数,结果截然不同.这是为啥呢??麻烦老师解答一下.以上的代码只是在线程数那里做了修改,其它地方都没改变.我的数据库也是和这个打印效果完全一样..
12
收起
正在回答 回答被采纳积分+1
3回答
2.Python操作三大数据库
- 参与学习 人
- 提交作业 625 份
- 解答问题 2669 个
数据库作为企业储存和管理数据的根本,掌握数据库是每个开发工程师必备的技能,本阶段带你学会用Python操作MySQL、Redis和MongoDB三大主流数据库。夯实数据库基础。
了解课程
恭喜解决一个难题,获得1积分~
来为老师/同学的回答评分吧