简单的python线程池实现线程安全demo

from concurrent.futures import ThreadPoolExecutor
import threading
import time
import sys
sys.path.append(sys.path)
test_list = [t for t in range(0,100)]
# 定义一个准备作为线程任务的函数
index = 0
lock = threading.Lock()
def action(thread_id):
    global index
    global test_list
    global lock
    while index<len(test_list):
        print(f'{thread_id}执行了!')
        try:
            # time.sleep(random.random())
            #time.sleep(random.randint(0, 3))
            lock.acquire()
            if index+1<len(test_list):
                index += 1
                callback(index)
            else:
                print(f'{thread_id}任务完成了!')
                return
        except BaseException as e:
            print(e)
        finally:
            lock.release()

def callback(index):
    print(test_list[index])

def start():

    # 创建一个包含4条线程的线程池
    with ThreadPoolExecutor(max_workers=4) as pool:
        # 使用线程执行map计算
        # 后面元组有3个元素,因此程序启动3条线程来执行action函数
        results = pool.map(action,(1,2,3,4))
        print('--------------')

if __name__ == '__main__':
    pass

 

posted @ 2022-05-10 17:12  冷光清坠落  阅读(138)  评论(0编辑  收藏  举报