Python-线程的基本使用

文章展示了Python中如何创建线程,包括继承`threading.Thread`和使用线程函数两种方式,并演示了生产者消费者模型的实现,利用`Queue`的原子操作确保数据同步。

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

# 线程类(继承threading.Thread并重写run方法):
class Produce(threading.Thread):
    def __init__(self):
        # 若子类重写了父类的__init__则一定要调用父类__init__正确继承父类变量和方法
        super().__init__()
        self.stat = "running"
    def run(self):
        print(self.stat)
        print("over run")

pro = Produce()
# start会自动执行run方法
pro.start()
# 等待主线程
pro.join()
# running
# over run

-------------------------------------------------------------

# 线程函数-多线程
# 第一个参数是线程函数变量,第二个参数args是一个元组参数,如果
# 只传递一个值,就只需要i, 如果需要传递多个参数,那么还可以继续传递
# 下去其他的参数,其中的逗号不能少,元组中只包含一个元素时,需要在
# 元素后面添加逗号。
import threading
import time
def worker(number):
    print “worker”
    time.sleep(number)

def multi_thread():
	for i in xrange(5):
    	t = threading.Thread(target=worker,args=(i,))
    	t.start()
    	t.join()

生产者与消费者

# 生产者生成随机数量个任务, 由消费者处理
# Queue的操作为原子操作, 自带锁
import threading, random
from queue import Queue
data_count = random.randint(1, 100)
task_que = Queue(data_count)
def Produce():
    print("Produce running")
    global task_que
    for i in range(data_count):
        print("生产数据资料中...")
        task_id = random.randint(1, 100)
        task_que.put(task_id)
        print("生成数据:", task_id)
    print("------------------ 生成数据量:%d --------------------"%(data_count))

def Spend():
    print("Spend running")
    over_task = 0
    global task_que
    while over_task != data_count:
        print("消耗数据资料中...")
        task_id = task_que.get()
        over_task += 1
        print("消耗数据:", task_id)
    print("------------------ 消耗数据量:%d --------------------"%(over_task))

produ_thr = threading.Thread(target=Produce)
spend_thr = threading.Thread(target=Spend)
spend_thr.start()
produ_thr.start()
spend_thr.join()
produ_thr.join()
print("over")

### Python 中进线程的概念 #### 进 (Process) 进是指操作系统结构中的基本单元,拥有独立的地址空间。每个进都有自己私有的数据段、堆栈区和全局变量等资源,在创建子进时会复制父进的数据副本[^3]。 - **优点** - 更高的稳定性:由于各进间相互隔离,一个进崩溃不会影响其他进- **缺点** - 创建销毁成本高:因为涉及内存分配等问题,所以开销较大。 - 数据共享困难:不同进之间传递消息较为复杂。 ```python from multiprocessing import Process, Queue def f(q): q.put([42, None, 'hello']) if __name__ == '__main__': queue = Queue() p = Process(target=f, args=(queue,)) p.start() print(queue.get()) # prints "[42, None, 'hello']" p.join() ``` #### 线程 (Thread) 线程是进中可调度运行的一个实体;同一进下的多个线程共享该进的所有资源,包括代码段、数据段等,但每个线程有自己的调用栈[^1]。 - **优点** - 启动速度快:相比于进来说更轻量级。 - 资源消耗少:不需要像启动新进那样占用大量系统资源。 - **缺点** - 容易受到GIL(Global Interpreter Lock)的影响,在CPU密集型任务上表现不佳。 - 如果某个线程发生异常,则可能会影响到整个序的安全性和可靠性。 ```python import threading class MyThread(threading.Thread): def run(self): print(f"{threading.current_thread().getName()} started") threads = [] for i in range(5): t = MyThread() threads.append(t) t.start() for thread in threads: thread.join() print("All threads finished execution.") ``` ### 应用场景分析 对于I/O 密集型操作(如文件读写、网络请求),推荐使用线程来处理,这样可以在等待期间让出 CPU 给其他线程继续工作,从而提高整体性能。 而对于计算密集型的任务(比如大规模数据分析或图像渲染),则更适合采用多进方案,以充分利用多核处理器的优势并绕过 GIL 的限制。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值