python使用多线程来执行函数

使用多线程来高效执行程序!

示例代码1:

generate_data.py

import random

for i in range(100):
    a = random.randint(10, 99)
    b = random.randint(10, 99)
    data = f'第{i+1}条数据\n'
    with open('text.txt', 'a', encoding='utf-8') as f:
        f.write(data)

main.py

import threading
import time
from queue import Queue


# 定义消费者
class Consumer(threading.Thread):

    def run(self) -> None:
        global queue
        while queue.qsize() > 0:
            msg = self.name + "消费了" + queue.get().replace('\n', '')
            print(msg)
            time.sleep(1)


def read_file():
    file_data = open('text.txt', 'r', encoding='utf-8')
    global queue
    for line in file_data:
        queue.put(line)
    file_data.close()


if __name__ == '__main__':
    queue = Queue()
    read_file()
    consumer_lst = []
    for _ in range(5):
        consumer = Consumer()
        consumer.start()
        consumer_lst.append(consumer)

    for consumer in consumer_lst:
        consumer.join()
    print("程序执行完毕!!!")

运行结果:

        在上面输出的结果过,使用print()打印的数据比较混乱,比较影响观看效果。这时对混乱输出可以做一定的处理。

        python多线程时并发并非并行,线程之间并非严格遵守顺序,这就会造成线程不安全的情况,例如print是自动添加换行的,在换行时可能线程不安全,导致换行和下一句输出发生混乱。

解决方案:

  • 手动输入换行符,例如print(url+'\n',end=''),以空字符结尾,在输出内容后面主动加入换行符,这样就不会存在错位的问题。
  • 对 print() 加锁

示例代码2:

import threading
import time
from queue import Queue

mutex = threading.RLock()


# 定义消费者
class Consumer(threading.Thread):

    # 定义多线程有序输出
    def order_output(self, data):
        print("+" * 10)
        print(data)
        print("*" * 10)

    def run(self) -> None:
        global queue
        while queue.qsize() > 0:
            msg = self.name + "消费了" + queue.get().replace('\n', '')
            # print(msg)
            # 方法一:手动输入换行符
            # print(msg + '\n', end='')
            # 方法二:使用锁
            with mutex:
                self.order_output(msg)
            time.sleep(1)


def read_file():
    file_data = open('text.txt', 'r', encoding='utf-8')
    global queue
    for line in file_data:
        queue.put(line)
    file_data.close()


if __name__ == '__main__':
    queue = Queue()
    read_file()
    consumer_lst = []
    for _ in range(5):
        consumer = Consumer()
        consumer.start()
        consumer_lst.append(consumer)

    for consumer in consumer_lst:
        consumer.join()
    print("程序执行完毕!!!")

运行结果:

有时候想知道程序执行的速度,我们可以添加进度条来显示出来。可以借助tqdm库来实现。

示例代码3:

import threading
import time
from queue import Queue
from tqdm import tqdm

mutex = threading.RLock()


# 定义消费者
class Consumer(threading.Thread):

    # 定义多线程有序输出
    def order_output(self, data):
        print("+" * 10)
        print(data)
        print("*" * 10)

    def run(self) -> None:
        global queue
        while queue.qsize() > 0:
            pbar.update(1)
            msg = self.name + "消费了" + queue.get().replace('\n', '')
            # print(msg)
            # 方法一:手动输入换行符
            print(msg + '\n', end='')
            # 方法二:使用锁
            # with mutex:
            #     self.order_output(msg)
            time.sleep(5)


def read_file():
    file_data = open('text.txt', 'r', encoding='utf-8')
    global queue
    total = 0
    for line in file_data:
        queue.put(line)
        total += 1
    file_data.close()
    return total


if __name__ == '__main__':
    queue = Queue()
    total = read_file()
    # 使用tqdm进度条
    pbar = tqdm(total=total, desc='Consumer')
    pbar.set_postfix(aa=total, bb=total - 1)
    consumer_lst = []
    for _ in range(5):
        consumer = Consumer()
        consumer.start()
        consumer_lst.append(consumer)

    for consumer in consumer_lst:
        consumer.join()
    print("程序执行完毕!!!")

运行结果:

  • 2
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 在 Python 中,可以使用 `threading` 模块来实现多线程调用函数。下面是一个简单的示例: ```python import threading def func(arg1, arg2): # 这里是函数体,根据需要编写具体的功能实现 # 创建线程对象,传入参数 t1 = threading.Thread(target=func, args=(arg1_value, arg2_value)) t2 = threading.Thread(target=func, args=(arg1_value, arg2_value)) # 启动线程 t1.start() t2.start() # 等待线程执行完毕 t1.join() t2.join() ``` 在上面的示例中,`target` 参数指定要执行函数,`args` 参数传入函数需要的参数列表。创建线程对象后,使用 `start()` 方法启动线程,使用 `join()` 方法等待线程执行完毕。 需要注意的是,Python 中的多线程并非真正意义上的并行,而是通过在不同的时间片内切换线程来实现“伪并行”。因此,在使用多线程时,需要注意线程间的同步和互斥问题,以避免出现竞态条件等问题。 ### 回答2: 在Python中,我们可以通过多种方式实现多线程调用函数。 一种方法是使用`threading`模块,其中的`Thread`类可以用于创建线程对象。我们可以先定义一个函数,然后将其作为参数传递给`Thread`的构造函数。例如: ```python import threading def my_function(): # 执行任务的代码 thread1 = threading.Thread(target=my_function) thread2 = threading.Thread(target=my_function) thread1.start() thread2.start() ``` 在这个例子中,我们首先定义了一个名为`my_function`的函数,这是我们想要在线程中执行的任务。然后我们创建了两个线程对象`thread1`和`thread2`,并将`my_function`作为参数传递给它们。最后我们调用线程的`start`方法来启动它们。 另一种方式是使用`concurrent.futures`模块中的`ThreadPoolExecutor`类。这个类可以用来创建一个线程池,实现多线程执行任务的效果。下面是一个例子: ```python from concurrent.futures import ThreadPoolExecutor def my_function(): # 执行任务的代码 with ThreadPoolExecutor(max_workers=2) as executor: executor.submit(my_function) executor.submit(my_function) ``` 在这个例子中,我们先定义了`my_function`函数,然后使用`ThreadPoolExecutor`创建了一个线程池,最大线程数设置为2。使用`executor.submit`方法,我们可以将需要执行函数提交给线程池。线程池会自动分配线程来执行任务。 无论使用哪种方式,多线程调用函数可以提高程序的执行效率,特别是在需要同时处理多个任务时。但要注意合理管理线程的数量,避免过多的线程导致资源浪费或者性能下降。 ### 回答3: Python 中可以使用多线程调用函数多线程是一种并发执行的方式,可以让多个函数同时运行。 在 Python 中,可以使用 threading 模块来创建和管理线程。首先,我们需要导入 threading 模块。然后,定义一个函数作为线程的执行体,可以在函数中实现具体的功能。接下来,使用 threading.Thread 类来创建一个线程对象,并传入需要执行函数作为参数。最后,调用线程对象的 start 方法来启动线程。 下面是一个简单的示例: ```python import threading # 定义线程的执行体 def print_numbers(): for i in range(1, 6): print(i) # 创建线程对象并传入需要执行函数 thread = threading.Thread(target=print_numbers) # 启动线程 thread.start() # 主线程继续执行其他操作 for i in range(6, 11): print(i) ``` 上面的代码中,我们定义了一个 print_numbers 函数,用于打印数字 1 到 5。然后,创建了一个线程对象,并传入 print_numbers 函数作为参数。最后,调用线程对象的 start 方法来启动线程。主线程继续执行打印数字 6 到 10 的操作。 通过多线程调用函数,可以实现并发执行的效果,提高程序的执行效率。但需要注意的是,在多线程编程中需要考虑线程的同步、共享资源的保护等问题,以避免出现线程安全问题。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值