1

I know in python, we can use time.sleep(1) to sleep the current thread for a second. But what I want is to let all the threads sleep, or there will be some concurrency issues with my program. Anybody know how to do that?

Chris Martin
  • 30,334
  • 10
  • 78
  • 137
Chico Lin
  • 11
  • 3
  • 1
    One thread abruptly changing the execution of another can create serious, even critical, thread safety issues if the changed thread is left in an inconsistent or invalid state. You'll likely want to use a cooperative approach, where each thread checks on its own to see if a request to sleep has been issued so that it can make sure its own state is consistent before sleeping. – scottb Jan 23 '16 at 23:29
  • What have you tried yourself so far? This , as @scottb mentions, may cause serious issues, as the threads may be doing crucial work. – Demitrian Jan 23 '16 at 23:30
  • You might want to build something like a thread pool. When you put one thread asleep, all the others will wait for it. Like so: http://stackoverflow.com/a/3034000/5818240 – JD Forster Jan 23 '16 at 23:34
  • The Javastic way to solve thread synchronization problems is not to use Thread.sleep (which is a sure-fire way to create non-portable code). Rather, a concurrency primitive like `CountDownLatch` is used. When a thread reaches a point where it must wait for all other threads to complete their work, the latch is decremented and that thread sleeps. When the latch reaches zero, all threads have completed their work and are synchronized. An event is then issued signalling the threads that they may continue. Python should have similar threading facilities. – scottb Jan 23 '16 at 23:46
  • One thread forcing other threads to sleep without their cooperation will create concurrency issues, not resolve them. This question is kind of like, "I've never built a suspension bridge, but it seems like it would make sense to build them out of cotton. How can I do that?" Learn the normal way first, then you can form competent judgments of unusual ways that might be better. – David Schwartz Jan 24 '16 at 00:20

1 Answers1

0

I suggest you to use Semaphores, RLocks, and/or Events.

Read the manual and enjoy it! ;-)