0

I want to use the multi-threading to simulate produce breads in our company, I want to every two seconds produce one bread:

import threading
import time

def run(n):
    print ("product--%s" %n)
    time.sleep(2)

start_time = time.time()

for i in range(30):
    t = threading.Thread(target=run, args=("bread-%s"%i,))
    t.start()

But it seems do not pause two seconds, it direct print all all the breads:

product--bread-1
product--bread-2
product--bread-3
product--bread-4
product--bread-5
product--bread-6
product--bread-7
product--bread-8
product--bread-9
product--bread-10
product--bread-12
product--bread-11
product--bread-13
product--bread-14
product--bread-15
product--bread-16
product--bread-17
product--bread-18
product--bread-19
product--bread-20
product--bread-21
product--bread-22
product--bread-23
product--bread-24
product--bread-25
product--bread-26
product--bread-27
product--bread-28
product--bread-29
product--bread-30

The time.sleep did not works for me, how to realize my requirement? I want to every two seconds produce one bread, not one time produce all of them.

1243916142
  • 365
  • 6
  • 17
  • your code is set up to *immediately* print the bread argument, and *then* sleep 2 seconds. so, when you execute this code, all the threads rush to print `product--bread-x` and only after doing so, do they sleep. – n1c9 Sep 28 '17 at 02:22
  • 1
    Welcome to SO. Please take the time to read [ask] and the links it contains. – wwii Sep 28 '17 at 02:28

1 Answers1

2

From the join() document:

join(timeout=None)

Wait until the thread terminates. This blocks the calling thread until the thread whose join() method is called terminates – either normally or through an unhandled exception –, or until the optional timeout occurs.

You can use the join() to wait the thread execute, join every new started thread.

for i in range(30):
    t = threading.Thread(target=run, args=("bread-%s"%i,))
    t.start()
    t.join()
aircraft
  • 25,146
  • 28
  • 91
  • 166