2

I am trying to make simulation of telecommunication network in order to test some routing algorithm. Requests come according to Poisson distribution and their holding times follow exponential distribution.

After finding route for some request Timer should be activated to update values of residual link capacities after expiration of specific holding time interval. I know that I can use threading.Timer to call some function with delay, but before holding time expires many other request will arrive and I need to run separate Timer for each of them.

Not related with my algorithm, today I tried to run this code:

    def hello(i):
       print i

    for i in range(0,10):
      t = threading.Timer(2,hello,[i])
      t.start()

I wanted to print numbers from range (0,10) in intervals of 2 seconds, but output is totally weird. After few seconds I got:

0
1
32

4
5
6
7
89

So, it seems that I cannot use Timer for this purpose. Do you have some idea how to solve this problem?

1
  • 3
    You're printing in 10 different threads, so their output will be interleaved (e.g. 3 and 2 on the same line). If you want to run this all in one thread and wait 2 seconds between each call, just use time.sleep(2) in your for loop and call hello(). Commented Jul 29, 2014 at 17:57

1 Answer 1

3

If two threads print at the same time, it's possible for one thread to start printing before another one finishes. This may cause two messages to appear on one line, or for two newlines in a row to be printed with no content.

You can prevent threads from accessing some resource at the same time using a Lock object. In your example, you would want to restrict access to print.

import threading

print_lock = threading.Lock()

def hello(i):
    #no other thread can execute `hello` as long as I hold this lock.
    print_lock.acquire()

    print i

    #I'm done printing. Other threads may take their turn now.
    print_lock.release()

for i in range(0,10):
    t = threading.Timer(2,hello,[i])
    t.start()

Result (one possibility of many):

1
2
0
4
3
6
5
8
7
9
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.