python多线程实例

多线程 

Thread是线程类,有两种使用方法,直接传入要运行的方法或

1.从Thread继承并覆盖run()

import threading
import time
class MyThread(threading.Thread):
    def __init__(self, n):
        super(MyThread, self).__init__()
        self.n = n
    def run(self):
        print("runnint task", self.n)
t1 = MyThread("t1")
t2 = MyThread("t2")
t1.start()  # runnint task t1
#t1.join()
t2.start()  # runnint task t2
#t2.join()

1.当用继承的方式去创建线程时,一定要重写父类的Run()方法
2.当线程的run()方法结束的时候,线程也结束
3.我们认为是无法完全控制线程的,但是我们可以通过一些方式来影响线程的调用
4.线程的几种状态 新建----就绪----运行-----死亡 等待(阻塞)主要出现就绪与运行之间

5.在UNIX平台上,当某个进程终结之后,该进程需要被其父进程调用wait,否则进程成为僵尸进程(Zombie)。所以,有必要对每个Process对象调用join()方法 (实际上等同于wait)。对于多线程来说,由于只有一个进程,所以不存在此必要性。

2.直接传入要运行的方法

"""
例1:
# 假定这是你的银行存款:
balance = 0
lock = threading.Lock()
def change_it(n):
    # 先存后取,结果应该为0:
    global balance
    balance = balance + n
    balance = balance - n

def run_thread(n):
    #lock = threading.Lock()
    global lock
    for i in range(100000):
        lock.acquire()
        try:
            # 放心地改吧:
            change_it(n)
        finally:
            # 改完了一定要释放锁:
            lock.release():
t1 = threading.Thread(target=run_thread, args=(5,))
t2 = threading.Thread(target=run_thread, args=(8,))
t1.start()
t2.start()
#t1.join()
#t2.join()
print balance

例2:
#新线程执行的代码:
def loop(fn,a,b):
    print fn,a,b
    print 'thread %s is running...',threading.current_thread().name
    n = 0
    while n < 5:
        n = n + 1
        print "thread %s>>>%s",threading.current_thread().name,n
        time.sleep(1)
    print "thrad %s end",threading.current_thread().name
print "thread %s is running...",threading.current_thread().name
filename = "tgets.csv"
t = threading.Thread(target=loop,name="LoopThread",args=(filename,5,5))
t.start()
t.join()
print "thread %s ended.",threading.current_thread().name

例3:
hehe=6
def f():
    global hehe
    print(hehe)
    hehe=3
f()
print(hehe)
"""

 

### Python多线程编程示例 #### 使用 `threading` 模块创建简单多线程程序 下面是一个简单的例子,展示了如何使用Python内置的`threading`模块来启动两个线程,分别打印不同的消息。 ```python import threading def print_numbers(): for i in range(5): print(f"Number {i}") def print_letters(): for letter in 'ABCDE': print(f"Letter {letter}") t1 = threading.Thread(target=print_numbers) t2 = threading.Thread(target=print_letters) t1.start() t2.start() t1.join() t2.join() ``` 这段代码定义了两个函数用于演示目的,并通过`Thread`对象实例化它们作为单独的任务运行。最后调用了`join()`等待所有子线程完成工作后再继续主线程[^1]。 #### 处理I/O密集型任务——文件读写操作 当处理像文件读取这样的I/O密集型任务时,利用多线程可以有效提升效率: ```python from threading import Thread import os def read_file(filename): with open(filename, 'r') as f: content = f.read() print(content[:10]) # 只显示前十个字符 threads = [] for file_name in ['file1.txt', 'file2.txt']: thread = Thread(target=read_file, args=(file_name,)) threads.append(thread) thread.start() for t in threads: t.join() ``` 在这个案例里,为每一个待读取的文件创建了一个新的线程去执行相应的任务,从而实现了并发读取多个文件的效果[^2]。 #### 利用线程池管理大量短期任务 对于需要频繁创建销毁短生命周期的工作单元来说,采用线程池是一种更为高效的解决方案: ```python from concurrent.futures import ThreadPoolExecutor urls = ["http://example.com", "http://another-example.org"] def fetch_url(url): response = requests.get(url) return response.status_code with ThreadPoolExecutor(max_workers=5) as executor: results = list(executor.map(fetch_url, urls)) print(results) ``` 这里引入了`concurrent.futures`中的`ThreadPoolExecutor`类来进行批量HTTP GET请求的操作,在实际应用中可以根据需求调整最大工作者数量(`max_workers`)参数以优化性能表现[^3]。 #### 数据库访问时确保线程安全性 考虑到数据库连接的安全性和稳定性问题,应当采取适当措施防止竞争条件的发生,比如让每个线程持有自己的数据库会话或者共享同一个带有锁定机制的连接资源: ```python import pymysql from queue import Queue from threading import Lock lock = Lock() connection_queue = Queue() def get_connection(): while True: conn = connection_queue.get() try: yield conn.cursor() finally: connection_queue.put(conn) # 初始化若干个数据库连接放入队列... connections = [pymysql.connect(host='localhost', user='root', password='', database='testdb') for _ in range(5)] for c in connections: connection_queue.put(c) def insert_data(data_item): with lock: # 加锁保护临界区 cursor_gen = get_connection().__next__() sql_query = """INSERT INTO table_name(column1, column2) VALUES (%s,%s);""" cursor_gen.execute(sql_query, data_item) cursor_gen.connection.commit() ``` 上述片段说明了怎样在线程间安全地共享MySQL数据库连接的方法之一,即借助于`Queue`和`Lock`组件构建一个受控环境下的连接分发器[^4]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小金子的夏天

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值