I have 3 threads, t1
, t2
, and t3
I want to start the thread each N min, For example
t1 should start randomly each [2, 4] min
t2 should start randomly each [10, 15] min
t3 should start randomly each [6, 9] min
And here is what i have so far
def attack(number, driver, sleep_time):
# Do stuff here
sleep(randint(sleep_time[0], sleep_time[1]) * 60)
return attack(number, driver, sleep_time)
if __name__ == '__main__':
t1 = threading.Thread(target=attack, args=(1, driver, [2, 4]))
t2 = threading.Thread(target=attack, args=(2, driver, [10, 15]))
t3 = threading.Thread(target=attack, args=(3, driver, [6, 9]))
t1.start()
t2.start()
t3.start()
I have no problem with early-stage, My problem is with long term ( 10 - 20 min )
I can't let t2
or t3
work When t1
is performing actual action ( not sleep duration )
So, I can't Use join
as I will have to wait for the sleep duration.
And I have no idea how to get random
involved if I removed the sleep duration from the attack
function.
QUESTION:
Is there a better way than having the sleep duration, inside attack
function?
Is there a way to tell other threads, "Am performing action wait for me to go to sleep"
All I want to do, Is to start all the threads that are interacting with the same element But don't work at the same time.
Any idea, suggestions, or link would be much appreciated.
CodePudding user response:
Is there a better way...?
Yes. Separate the idea of a "thread" from the work that a thread does. If you don't want to ever have more than one thread "doing stuff here," then there's no reason to have more than one thread.
One thread could;
- Choose initial due-dates for each of the three activities,
- Figure out which activity is due next (i.e., find the min() of the due-dates,) and then sleep() until that one is due,
- do the activity,
- Add an appropriate random() amount of time to the due-date for the activity it just did,
- and go back to step 2.