0

I have the following code. I need to pause and resume randomly 1 of the threads I know how to random choice but how to pause them and resume later the thread. I look around over the all answers nothing work for me, I try with lock the thread is not locking I try with event again I don't manage to pause the thread. Any help is welcome. I am not a python developer, I just do a project.

def fistLoop():
for x in range(0,10):
    print(str(x) + " this is first loop")
    time.sleep(10)
def secondLoop():
    for x in range(10,20):
        print(str(x) + " second loop")
        time.sleep(10)


first = threading.Thread(target=fistLoop, args=())
second = threading.Thread(target=secondLoop, args=())

threadList = list()
first.start()
second.start()
mikegrep
  • 27
  • 7
  • Do the answers to this [question](https://stackoverflow.com/questions/10525185/python-threading-how-do-i-lock-a-thread) help at all? – quamrana Aug 13 '22 at 11:35
  • Your update has butchered your code. Please fix it. But be careful. If you change things too much you will invalidate the current excellent answer. – quamrana Aug 13 '22 at 12:55
  • I will leave it like it was – mikegrep Aug 13 '22 at 13:13

1 Answers1

2

Couldn't you use a lock? I don't completely understand what you mean by randomly pause one of the threads. I think you want something like this

from threading import Lock, Thread
import time
import random

locks = [Lock(), Lock()]

def fistLoop(lock):
    for x in range(0,10):
        with lock:
            print(str(x) + " this is first loop")
            time.sleep(1)
def secondLoop(lock):
    for x in range(10,20):
        with lock:
            print(str(x) + " second loop")
            time.sleep(1)



first = Thread(target=fistLoop, args=(locks[0],))
second = Thread(target=secondLoop, args=(locks[1],))

l = random.choice(locks)
l.acquire()
first.start()
first.start()
second.start()
time.sleep(3)
l.release()

Since each thread uses a different lock, acquiring one of those locks blocks one thread from executing until it is released. You could find a way to acquire the thread while the thread is running, but I can't figure out that far right now.

Ciro García
  • 601
  • 5
  • 22