Python 多线程中使用各自独立的变量

在Python多线程编程中,为确保线程间数据隔离,通常需要每个线程拥有自己的私有变量。文章探讨了如何在Python中实现这一目标,提供了一种优于直接使用私有变量的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

最简单的思路是每个 线程都使用各自私有的变量,但是python提供了一种更佳的解决方案

#!/usr/bin python
# -*- coding:utf-8 -*-
'''
Created on 2015-6-20

@author: huangpeng
threading.local 线程中使用各自独立的局部变量
'''
import threading
import random, time

class ThreadLocal():
    def __init__(self):
        self.local = threading.local()
    def run(self):
        time.sleep(random.random())
        self.local.number =[]
        for i in range (10):
            self.local.number.append(random.choice(range(10)))
        print threading.currentThread(), self.local.number

threadLocal = ThreadLocal()
threads = []
for i in range(5):
    t = threading.Thread(target=threadLocal.run)
    t.start()
    threads.append(t)
for i in range(5):
    threads[i].join

console:

<Thread(Thread-2, started 140011638880000)> [4, 0, 1, 8, 0, 6, 3, 1, 1, 3]
<Thread(Thread-1, started 140011722458880)> [5, 5, 4, 0, 5, 7, 8, 6, 0, 7]
<Threa
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值