ThreadPool in Python

 from concurrent.futures import ThreadPoolExecutor

import asyncio
import time
import threading

x = 1


def run_forever1(lock):
global x

while x < 1000:
print(f'----start1 acc------{threading.current_thread().name}-')
lock.acquire()
print(f'----start1 acced------{threading.current_thread().name}-')

if x < 1000:
print(f'----run 1------{threading.current_thread().name}-')
x = x + 1
lock.release()
print(f'----start1 release------{threading.current_thread().name}-')


def run_forever2(lock):
global x

while x < 1000:
print(f'----start2 acc------{threading.current_thread().name}-')
lock.acquire()
print(f'----start2 acced------{threading.current_thread().name}-')

if x < 1000:
print(f'----run 2------{threading.current_thread().name}-')
x = x + 1
lock.release()
print(f'----start2 release------{threading.current_thread().name}-')


def main():
print('----x-------')
lock = threading.Lock()

with ThreadPoolExecutor(max_workers=3) as ex:
asyncio.get_event_loop().run_in_executor(ex, run_forever1, lock)
asyncio.get_event_loop().run_in_executor(ex, run_forever2, lock)

global x

# while True:
print(f'-----------run 3-----{x}--')
# time.sleep(4)


if __name__ == '__main__':
main()

Comments

Popular posts from this blog

Fixing the DeepSpeed Import Error While Fine-Tuning the Qwen Model

Amazon Linux 2023 - User data configuration for launch templates to connect to the EKS cluster

How to create ISM policy and rotate logs in opensearch