python 多线程 记录

python 爬虫 多用户 定量

程序:

import time
import json
import threading 

num = 0
num_lock = threading.Lock()  
main_lock = True

stop_event = threading.Event()  

def process_user(user):  
    print('--------',user['user_name'],'-----------')
    global num ,main_lock ,num_lock,stop_event
    
    cont = 0
    while True:
        # with num_lock:
            num = num + 1
            cont = cont + 1
            print(user['user_name'],num)
            
            if num >= 20 :
                print(num)
                main_lock = False
                stop_event.set()
                break

            
            time.sleep(1)
            if cont >= 4 :
                break
    # 当num 累加到500的时候停止程序,应该怎样修改
def main():
    userinfo = [
        {
            "user_name":'001'
        },
                {
            "user_name":'002'
        },
        {
            "user_name":'003'
        },
    ]
    threads = []  
    for user in userinfo: 
        time.sleep(0.99)  # 每个用户之间间隔 0.99 秒
        t = threading.Thread(target=process_user, args=(user,))  
        t.start()  
        threads.append(t)
  
    # 等待所有线程完成  
    for t in threads:  
        t.join()
  
if __name__ == "__main__":  
    try:  
        while main_lock: 
            main()  
    except KeyboardInterrupt:  
        print("程序被手动终止")
        stop_event.set()  # 手动终止时,也设置stop_event以确保所有线程都能停止  
    finally:
        print('程序终止!!!')

运行结果:

-------- 001 -----------
001 1
-------- 002 -----------
002 2
001 3
-------- 003 -----------
003 4
002 5
001 6
003 7
002 8
001 9
003 10
002 11
003 12
-------- 001 -----------
001 13
-------- 002 -----------
002 14
001 15
-------- 003 -----------
003 16
002 17
001 18
003 19
002 20
20
001 21
21
003 22
22
程序终止!!!

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值