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


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, ())


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

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


Multimedia Modules

Data Storage

Tools and Utilities

Platform-Specific Modules

Implementation Support Modules

Other Modules

Python Standard Library
Python Standard Library (Nutshell Handbooks) with
ISBN: 0596000960
EAN: 2147483647
Year: 2000
Pages: 252
Authors: Fredrik Lundh © 2008-2020.
If you may any questions please contact us: