Python Programming/Threading
From Wikibooks, the open-content textbooks collection
| Previous: Email | Index | Next: Sockets |
[edit] A Minimal Example
#!/usr/bin/env python import threading import time class MyThread(threading.Thread): def run(self): print "%s started!" % self.getName() time.sleep(1) print "%s finished!" % self.getName() if __name__ == '__main__': for x in range(4): mythread = MyThread(name = "Thread-%d" % (x + 1)) mythread.start() time.sleep(.2)
This should output:
Thread-1 started! Thread-2 started! Thread-3 started! Thread-4 started! Thread-1 finished! Thread-2 finished! Thread-3 finished! Thread-4 finished!
Note: this example appears to crash IDLE in Windows XP
There seems to be a problem with this, if you replace Sleep(1) with (2) ,and change range (4) to range(10). Thread -2 finished is the first line before its even started. in WING IDE, Netbeans, eclipse is fine.
[edit] A Minimal Example with Function Call
Make a thread that prints numbers from 1-10, waits for 1 sec between:
import thread, time def loop1_10(): for i in range(1,10): time.sleep(1) print i thread.start_new_thread(loop1_10, ())
| Previous: Email | Index | Next: Sockets |

