欢迎访问宙启技术站
智能推送

Python中多进程和多线程的函数

发布时间:2023-06-06 09:45:50

Python是一门高级编程语言,具有简单易学,易读易写等特点,性能优越,支持多线程和多进程编程。Python提供了多线程和多进程的模块,让我们可以利用多核CPU的优势,提高程序的效率。

一、多线程

多线程是指在一个进程内部,有多个并发执行的线程,每个线程都可以独立执行不同的任务。Python的多线程模块包括thread和threading两个,thread是低级模块,提供了基本的线程创建函数,而threading是高级模块,提供了更多访问线程的方法和属性。

1. 创建线程

多线程的创建有两种方式:

(1)继承Thread类

import threading

class myThread(threading.Thread):
    def __init__(self, threadID, name, counter):
        threading.Thread.__init__(self)
        self.threadID = threadID
        self.name = name
        self.counter = counter
    def run(self):
        print ("开始线程:" + self.name)
        print_time(self.name, self.counter, 5)
        print ("退出线程:" + self.name)

def print_time(threadName, delay, counter):
    while counter:
        time.sleep(delay)
        print ("%s: %s" % (threadName, time.ctime(time.time())))
        counter -= 1
        
t1 = myThread(1, "Thread-1", 1)
t2 = myThread(2, "Thread-2", 2)

t1.start()
t2.start()

t1.join()
t2.join()

(2)实例化Thread类

import threading

def print_time(threadName, delay, counter):
    while counter:
        time.sleep(delay)
        print ("%s: %s" % (threadName, time.ctime(time.time())))
        counter -= 1

def create_new_thread():
    t = threading.Thread(target=print_time, args=('Thread-1', 1, 5))
    t.start()

create_new_thread()

2. 线程运行

线程创建完毕后,用start方法执行线程,线程开始执行run方法。

t1.start()

线程执行结束后,使用join等待线程结束。

t1.join()

3. 线程同步

当多个线程同时访问共享资源时,可能会出现数据竞争的问题,导致程序出错。为了避免上述问题,Python提供了多种锁机制,如互斥锁、条件锁、信号量等。下面是一个互斥锁的例子。

import threading

class myThread (threading.Thread):
    def __init__(self, threadID, name, counter):
        threading.Thread.__init__(self)
        self.threadID = threadID
        self.name = name
        self.counter = counter
    def run(self):
        print ("开始线程:" + self.name)
        threadLock.acquire()
        print_time(self.name, self.counter, 5)
        threadLock.release()
        print ("退出线程:" + self.name)

def print_time(threadName, delay, counter):
    while counter:
        time.sleep(delay)
        print ("%s: %s" % (threadName, time.ctime(time.time())))
        counter -= 1

threadLock = threading.Lock()
threads = []

t1 = myThread(1, "Thread-1", 1)
t2 = myThread(2, "Thread-2", 2)

t1.start()
t2.start()

threads.append(t1)
threads.append(t2)

for t in threads:
    t.join()

print ("退出主线程")

二、多进程

多进程是指在一个操作系统中有多个并发执行的进程,每个进程都可以独立执行不同的任务。Python的多进程模块有multiprocessing和os两个。

1. 创建进程

多进程的创建有两种方式:

(1)Process类

import multiprocessing

def print_time(name, delay, counter):
    while counter:
        time.sleep(delay)
        print ("%s: %s" % (name, time.ctime(time.time())))
        counter -= 1

if __name__ == '__main__':
    p1 = multiprocessing.Process(target=print_time, args=("Process-1", 1, 5))
    p2 = multiprocessing.Process(target=print_time, args=("Process-2", 2, 4))

    p1.start()
    p2.start()

    p1.join()
    p2.join()

    print ("退出主进程")

(2)Pool类

import multiprocessing

def print_time(name, delay, counter):
    while counter:
        time.sleep(delay)
        print ("%s: %s" % (name, time.ctime(time.time())))
        counter -= 1

if __name__ == '__main__':
    pool = multiprocessing.Pool(processes=2)

    pool.apply_async(print_time, args=("Pool-1", 1, 5))
    pool.apply_async(print_time, args=("Pool-2", 2, 4))

    pool.close()
    pool.join()

    print ("退出主进程")

2. 进程间通信

两个或多个进程彼此之间不能直接共享内存,因此进程之间通信需要使用到multiprocessing模块中的Queue、Pipe、Manager等。一个简单的例子:

import multiprocessing

def write(queue):
    for value in ['A', 'B', 'C']:
        print ('Put %s to queue...' % value)
        queue.put(value)
        time.sleep(1)

def read(queue):
    while True:
        if not queue.empty():
            value = queue.get()
            print ('Get %s from queue.' % value)
            time.sleep(1)
        else:
            break

if __name__ == '__main__':
    queue = multiprocessing.Queue()
    proc_write = multiprocessing.Process(target=write, args=(queue,))
    proc_read = multiprocessing.Process(target=read, args=(queue,))

    proc_write.start()
    proc_read.start()

    proc_write.join()
    proc_read.terminate()

以上就是Python中多进程和多线程的函数,各有优劣,选择使用时需要根据具体情况进行权衡。