The thread Module

(Optional) The thread module provides a low-level interface for threading, as shown in Example 3-6. It's only available if your interpreter is built with thread support. New code should use the higher-level interface in the threading module instead.

Example 3-6. Using the thread Module

File: thread-example-1.py

import thread
import time, random

def worker():
 for i in range(50):
 # pretend we're doing something that takes 10100 ms
 time.sleep(random.randint(10, 100) / 1000.0)
 print thread.get_ident(), "-- task", i, "finished"

#
# try it out!

for i in range(2):
 thread.start_new_thread(worker, ())

time.sleep(1)

print "goodbye!"

311 -- task 0 finished
265 -- task 0 finished
265 -- task 1 finished
311 -- task 1 finished
...
265 -- task 17 finished
311 -- task 13 finished
265 -- task 18 finished
goodbye!

Note that when the main program exits, all threads are killed. The threading module doesn't have that problem.

Core Modules

More Standard Modules

Threads and Processes

Data Representation

File Formats

Mail and News Message Processing

Network Protocols

Internationalization

Multimedia Modules

Data Storage

Tools and Utilities

Platform-Specific Modules

Implementation Support Modules

Other Modules

show all menu



Python Standard Library
Python Standard Library (Nutshell Handbooks) with
ISBN: 0596000960
EAN: 2147483647
Year: 2000
Pages: 252
Authors: Fredrik Lundh
Similar book on Amazon

Flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net