Python 进程和线程

本文深入探讨了Python中的进程和线程。在进程中,通过Manager实现了子进程与主进程间变量的共享。而在线程中,主线程与子线程能方便地共享资源,示例分别展示了如何使用非成员函数和成员函数创建线程。通过实例代码,详细解释了线程的创建和资源共享机制。

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

欢迎访问我的博客首页

1. 进程


  不能使用成员函数创建进程,而且子进程与主进程共享变量需要借助 Manager。

#encoding=utf-8
 
from multiprocessing import Process, Manager
import os
import time
 
def process_fac(bill, ID, interval, **kwargs):
    # 字典参数使用示例
    bill.append(kwargs['BMW'])
    bill.append(kwargs['Audi'])
 
    # 整型参数使用示例
    ID.value = os.getpid()
 
    # 列表参数使用示例
    x = 1
    while(True):
	bill.append(x)
	x += 1
    	time.sleep(interval)
 
if __name__ == '__main__':
    # 共享参数
    manager = Manager()
    bill = manager.list()
    ID = manager.Value('i', 0)
 
    p = Process(target = process_fac,
		name = 'subprocess_1',
                args = (bill, ID, 1),
                kwargs = {'BMW': 298, 'Audi': 180})
    p.start()
 
    time.sleep(5)
    p.terminate()
    print bill
    print ID.value

2. 线程


  主线程及其子线程共享资源,所以使用线程很容易实现资源共享。Python 有 _thread 和 threading 两个线程包,其中后者功能更多。它们都可以使用成员函数和非成员函数创建线程。

2.1 使用非成员函数创建线程


  下面的程序使用 _thread 包和非成员函数创建线程,换作 threading 也是可以的。使用 start_new_thread 函数创建线程即开始运行,没有 start 函数;即使不传参,第二个参数位置也要有个小括号。

import time
import _thread

def progress_fac(y):
    a = 1
    while True:
        y.append(a)
        a += 1
        time.sleep(1)

if __name__ == '__main__':
    y = []
    _thread.start_new_thread(progress_fac, (y,))
    time.sleep(10)
    print(y)

2.2 使用成员函数创建线程


  下面的程序使用 threading 包和成员函数创建线程,换作 _thread 也是可以的。使用成员函数创建线程,在线程函数中可以正常访问成员变量。

import time
import threading

class Example:
    def __init__(self):
        super(Example, self).__init__()
        self.value = 17
        self.stop_thread = False

    def go(self):
        # t = threading.Thread(target=Example.fac, args=(self,))
        t = threading.Thread(target=self.fac)
        t.start()
        time.sleep(10)
        self.stop_thread = True

    def fac(self):
        while not self.stop_thread:
            print('v = ', self.value)
            self.value += 1
            time.sleep(1)

if __name__ == '__main__':
    ex = Example()
    ex.go()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值