#1
  1. No Profile Picture
    Contributing User
    Devshed Novice (500 - 999 posts)

    Join Date
    Nov 2004
    Location
    There where the rabbits jump
    Posts
    556
    Rep Power
    11

    Threading Module


    Hi

    I was wondering what the Thearding module does and how it works and what I could use it for?

    Please give some type of info or link to info
    Those people who think they know everything are a great annoyance to those of us who do.
  2. #2
  3. No Profile Picture
    Contributing User
    Devshed Novice (500 - 999 posts)

    Join Date
    Nov 2003
    Posts
    624
    Rep Power
    34
    It's used for writing threaded programs.

    If you imagine what happens when you write:

    Code:
    print 1
    name = raw_input("What is your name?")
    print 2
    The program will wait until you enter your name before it prints the number 2.

    This is no good for a program that needs to send data over the network every second, or one that has to watch the CPU temperature - if they stopped for you to type, they would stop working.

    Threads are a way around this.

    Each thread is a piece of your program running at the same time as all the other threads. Like having Internet Explorer and Notepad open at the same time - but on a smaller scale.

    Lots of small bits of code running at the same time within your overall program.

    e.g. (pseudo code)
    Code:
    from threading import Thread
    import time
    
    def net(): 
       connect_to_server()
       while True:
            send_data()
            time.sleep(1)
    
    def watch_temp():
        while True:
            if get_temp() > 50:
                alarm()
            time.sleep(1)
    
    thread1 = Thread(net)
    thread1.start()
    
    thread2 = Thread(watch_temp)
    thread2.start()
    
    print "monitoring"
    name = raw_input("I am monitoring stuff, talking on the network and I can still ask your name...")
    print "hi", name

    I don't know of any good links, but I'm sure Google has some HOWTO's around.

    Comments on this post

    • SimonGreenhill agrees
  4. #3
  5. No Profile Picture
    Contributing User
    Devshed Novice (500 - 999 posts)

    Join Date
    Nov 2004
    Location
    There where the rabbits jump
    Posts
    556
    Rep Power
    11
    okay now i sort of get it so it is mostly for loops since that usually blocks the program

    because i tried one before with print and it did not really help me. So it basicly branches the program and the program continues on both branches
    Those people who think they know everything are a great annoyance to those of us who do.
  6. #4
  7. Contributing User
    Devshed Intermediate (1500 - 1999 posts)

    Join Date
    Dec 2004
    Location
    Meriden, Connecticut
    Posts
    1,797
    Rep Power
    154
    The threading module also contains a Timer() function. Where it can run a specified function within a specified amount of secods. This can be helpful for running large applications and you don't want to cause your program to freeze up at times. Also, when playing sounds through an application, the Timer() module will keep the program from pausing while playing the sound.
  8. #5
  9. No Profile Picture
    Contributing User
    Devshed Novice (500 - 999 posts)

    Join Date
    Nov 2003
    Posts
    624
    Rep Power
    34
    okay now i sort of get it so it is mostly for loops since that usually blocks the program
    Yes; the most commonly talked about uses are;

    - Responsiveness: If you have a fairly intensive process running, and you also have a bit of code that interacts with the user, you don't want the user code to wait for a break in the intensive code before it can respond to a keypress (or you might press a key and wait 5 seconds for anything to happen), so you set the interface code in its own thread to keep the program feeling fast and responsive.

    - Background processing: If you want something happening all the way through your program - something you can setup and then pretty much forget about, e.g. music playing.

    - Network servers: The main part of the program is dedicated to listening for connections from clients, and it spawns a thread to handle all the talking to each new client.

    So it basicly branches the program and the program continues on both branches
    Yes. Or all three branches, or however many you have.

    (There is some overhead to Threads, and there are possible problems you have to be careful of if you want to use them.
    For instance, if you have three threads all calculating, and you want to print the results, you might do:

    Code:
    def calc(n):
        result = n * 2
        print result
    
    thread1 = Thread(calc(1)).run()
    thread2 = Thread(calc(10)).run()
    thread3 = Thread(calc(25)).run()
    
    print "Hello, the results for 1, 10 and 25 are:"
    However, because the threads all run at roughly the same time, you don't know which will finish first - or if they will finish soon and start printing answers before you even print the Hello bit. But yes, that is what they do.)
    Last edited by sfb; June 11th, 2005 at 07:37 PM.
  10. #6
  11. No Profile Picture
    Contributing User
    Devshed Novice (500 - 999 posts)

    Join Date
    Nov 2004
    Location
    There where the rabbits jump
    Posts
    556
    Rep Power
    11
    how could I make a function print the stuff when I want it to

    and

    Why by this

    Code:
    >>> class Def:
    	def __init__(self):
    		def Sysexit():
    			import time
    			time.sleep(10)
    			print "exit"
    		def Talk():
    			d = raw_input()
    			print d
    		thread1 = threading.Thread(Sysexit()).start()
    		thread2 = threading.Thread(Talk()).start()
    can't I have the raw_input() accept the text I typed and print it it never works except when the first thread ends?
    Last edited by monkeyman23555; June 12th, 2005 at 05:53 AM.
    Those people who think they know everything are a great annoyance to those of us who do.
  12. #7
  13. Contributing User
    Devshed Intermediate (1500 - 1999 posts)

    Join Date
    Dec 2004
    Location
    Meriden, Connecticut
    Posts
    1,797
    Rep Power
    154
    No...Use the Timer() function. Here is an example (by the way, this is all documented on python.org):
    Code:
    from threading import *
    def hello():
        print 'hello world'
    Timer(s, hello).start() # s is the amount of seconds, it can be int or float
    The function can never hold any arguments when using this function, if you needed to call arguments with it, you would need to call them by reference.
  14. #8
  15. The Thief of Time
    Devshed Newbie (0 - 499 posts)

    Join Date
    Oct 2003
    Location
    Lisbon, Portugal
    Posts
    276
    Rep Power
    11
    Hello,

    I just started coding in Python (great language btw) and have a special interest in threads since I come from C and Java college projects where I used threads in several ocasions.
    Tried the code posted by one of the users which called a 'calc' function but it obviously wasn't working for more than one reason...
    I took a look at the docs and came up with a simple code that explains the thread purpose.
    Code:
    from threading import Thread
    
    def fibonacci(n):
      if n == 0 or n == 1:
        return 1
      else:
        return fibonacci(n-1) + fibonacci(n-2)
    
    def calc(n):
      print fibonacci(n),"< fibonacci",n
    
    thread1 = Thread(target=calc, args=[29])
    thread2 = Thread(target=calc, args=[28])
    thread3 = Thread(target=calc, args=[27])
    thread4 = Thread(target=calc, args=[26])
    
    thread1.start()
    thread2.start()
    thread3.start()
    thread4.start()
    
    print "Hello, the fibonacci numbers for 27,28,29,30 are:"
    If you run this code a few times you will see that it doesn't always output the same results.

    One thing that confused me was the docs on the Thread __init__ method:
    args is the argument tuple for the target invocation. Defaults to ().
    Well, I tried passing a tuple but it complained that it had to be a sequence? Docs need to be updated?
    Last edited by Lobsang; June 16th, 2005 at 03:21 AM.
  16. #9
  17. Contributing User
    Devshed Intermediate (1500 - 1999 posts)

    Join Date
    Dec 2004
    Location
    Meriden, Connecticut
    Posts
    1,797
    Rep Power
    154
    I think you should look into the threading module's Timer() function.
  18. #10
  19. No Profile Picture
    Contributing User
    Devshed Novice (500 - 999 posts)

    Join Date
    Nov 2004
    Location
    There where the rabbits jump
    Posts
    556
    Rep Power
    11
    Why is the Timer() so good I mean what are the seconds for, how long it gets executed or after how long it start being executed?
    Those people who think they know everything are a great annoyance to those of us who do.
  20. #11
  21. Contributing User
    Devshed Intermediate (1500 - 1999 posts)

    Join Date
    Dec 2004
    Location
    Meriden, Connecticut
    Posts
    1,797
    Rep Power
    154
    The seconds determine the time in which the function will be executed. If you simply want it to be executed instantly, set the seconds to 0. When you use the Timer() function, as other threading functions do the same, other tasks can be run at the same time, without taking up the process on the Timer() functions' space. This fucntion works great for playing sounds or reading large amounts of data from a file, when normally your program would slow down greatly. I find the Timer() function a big help.
  22. #12
  23. No Profile Picture
    Contributing User
    Devshed Novice (500 - 999 posts)

    Join Date
    Nov 2004
    Location
    There where the rabbits jump
    Posts
    556
    Rep Power
    11
    okay now i get it thanks
    Those people who think they know everything are a great annoyance to those of us who do.

IMN logo majestic logo threadwatch logo seochat tools logo