Python Tutorial ( PDFDrive )
CHAPTER24Python MultithreadingRunning several threads is similar to running several different programs concurrently, but with thefollowing benefits:• Multiple threads within a process share the same data space with the main thread and can therefore shareinformation or communicate with each other more easily than if they were separate processes.• Threads sometimes called light-weight processes and they do not require much memory overhead; they carecheaper than processes.A thread has a beginning, an execution sequence, and a conclusion. It has an instruction pointer that keeps trackof where within its context it is currently running.• It can be pre-empted (interrupted)• It can temporarily be put on hold (also known as sleeping) while other threads are running - this is calledyielding.Starting a New Thread: To spawn another thread, you need to call following method available in thread module:thread.start_new_thread ( function, args[, kwargs] )This method call enables a fast and efficient way to create new threads in both Linux and Windows.The method call returns immediately and the child thread starts and calls function with the passed list of agrs.When function returns, the thread terminates.Here, args is a tuple of arguments; use an empty tuple to call function without passing any arguments. kwargs isan optional dictionary of keyword arguments.EXAMPLE: #!/usr/bin/pythonimport threadimport time# Define a function for the threaddef print_time( threadName, delay):TUTORIALS POINT Simply Easy Learning
count = 0while count < 5:time.sleep(delay)count += 1print "%s: %s" % ( threadName, time.ctime(time.time()) )# Create two threads as followstry:thread.start_new_thread( print_time, ("Thread-1", 2, ) )thread.start_new_thread( print_time, ("Thread-2", 4, ) )except:print "Error: unable to start thread"while 1:passWhen the above code is executed, it produces the following result:Thread-1: Thu Jan 22 15:42:17 2009Thread-1: Thu Jan 22 15:42:19 2009Thread-2: Thu Jan 22 15:42:19 2009Thread-1: Thu Jan 22 15:42:21 2009Thread-2: Thu Jan 22 15:42:23 2009Thread-1: Thu Jan 22 15:42:23 2009Thread-1: Thu Jan 22 15:42:25 2009Thread-2: Thu Jan 22 15:42:27 2009Thread-2: Thu Jan 22 15:42:31 2009Thread-2: Thu Jan 22 15:42:35 2009Although it is very effective for low-level threading, but the thread module is very limited compared to the newerthreading module.The Threading Module: The newer threading module included with Python 2.4 provides much more powerful, high-level support forthreads than the thread module discussed in the previous section.The threading module exposes all the methods of the thread module and provides some additional methods:• threading.activeCount(): Returns the number of thread objects that are active.• threading.currentThread(): Returns the number of thread objects in the caller's thread control.• threading.enumerate(): Returns a list of all thread objects that are currently active.In addition to the methods, the threading module has the Thread class that implements threading.The methods provided by the Thread class are as follows:• run(): The run() method is the entry point for a thread.• start(): The start() method starts a thread by calling the run method.• join([time]): The join() waits for threads to terminate.• isAlive(): The isAlive() method checks whether a thread is still executing.• getName(): The getName() method returns the name of a thread.• setName(): The setName() method sets the name of a thread.Creating Thread using Threading Module: To implement a new thread using the threading module, you have to do the following:• Define a new subclass of the Thread class.• Override the __init__(self [,args]) method to add additional arguments.TUTORIALS POINT Simply Easy Learning
- Page 305 and 306: ......................else:If there
- Page 307 and 308: print "Error: can\'t find file or r
- Page 309 and 310: self.args = argSo once you defined
- Page 311 and 312: 'Optional class documentation strin
- Page 313 and 314: For the above class let's try to ac
- Page 315 and 316: print 'Calling child method'c = Chi
- Page 317 and 318: Data Hiding: An object's attribute
- Page 319 and 320: groups()This method returns all mat
- Page 321 and 322: SYNTAX: re.sub(pattern, repl, strin
- Page 323 and 324: \s Matches whitespace. Equivalent t
- Page 325 and 326: Backreferences: This matches a prev
- Page 327 and 328: CHAPTER20Python CGI ProgrammingWhat
- Page 329 and 330: If you click hello.py, then this pr
- Page 331 and 332: Simple URL Example : Get Metho
- Page 333 and 334: </form>The result of this code is t
- Page 335 and 336: text_content = form.getvalue('textc
- Page 337 and 338: Here is an example of how to retrie
- Page 339 and 340: CHAPTER21Python Database AccessThe
- Page 341 and 342: EXAMPLE: Following is the example o
- Page 343 and 344: ('Mac', 'Mohan', 20, 'M', 2000)try:
- Page 345 and 346: DELETE Operation: DELETE operation
- Page 347 and 348: ProgrammingErrorSubclass of Databas
- Page 349 and 350: The socket Module: To create a so
- Page 351 and 352: Protocol Common function Port No Py
- Page 353 and 354: Subject: SMTP e-mail testThis is a
- Page 355: try:smtpObj = smtplib.SMTP('localho
- Page 359 and 360: Synchronizing Threads: The threadi
- Page 361 and 362: thread = myThread(threadID, tName,
- Page 363 and 364: <stars>10</stars><description>Talk
- Page 365 and 366: print "Rating:", self.ratingelif se
- Page 367 and 368: Format: DVDRating: PGDescription: T
- Page 369 and 370: Tkinter Widgets Tkinter provides v
- Page 371 and 372: fgfontheighthighlightcolorimagejust
- Page 373 and 374: WidthXscrollincrementXscrollcommand
- Page 375 and 376: pattern when it is over the checkbu
- Page 377 and 378: The Entry widget is used to accept
- Page 379 and 380: E1 = Entry(top, bd =5)E1.pack(side
- Page 381 and 382: Optionanchorbgbitmapbdcursorfontfgh
- Page 383 and 384: selectmodeDetermines how many items
- Page 385 and 386: Syntax: Here is the simple syntax t
- Page 387 and 388: Menu The goal of this widget is to
- Page 389 and 390: filemenu.add_command(label="Exit",
- Page 391 and 392: Example: Try the following example
- Page 393 and 394: WidthWraplengthWidth of the label i
- Page 395 and 396: label appears in the top left corne
- Page 397 and 398: Parameters: • master: This repres
- Page 399 and 400: Parameters: • master: This repres
- Page 401 and 402: mark_gravity(mark [,gravity])Return
- Page 403 and 404: Methods & Descriptiondeiconify()Dis
- Page 405 and 406: disabledbackgrounddisabledforegroun
count = 0
while count < 5:
time.sleep(delay)
count += 1
print "%s: %s" % ( threadName, time.ctime(time.time()) )
# Create two threads as follows
try:
thread.start_new_thread( print_time, ("Thread-1", 2, ) )
thread.start_new_thread( print_time, ("Thread-2", 4, ) )
except:
print "Error: unable to start thread"
while 1:
pass
When the above code is executed, it produces the following result:
Thread-1: Thu Jan 22 15:42:17 2009
Thread-1: Thu Jan 22 15:42:19 2009
Thread-2: Thu Jan 22 15:42:19 2009
Thread-1: Thu Jan 22 15:42:21 2009
Thread-2: Thu Jan 22 15:42:23 2009
Thread-1: Thu Jan 22 15:42:23 2009
Thread-1: Thu Jan 22 15:42:25 2009
Thread-2: Thu Jan 22 15:42:27 2009
Thread-2: Thu Jan 22 15:42:31 2009
Thread-2: Thu Jan 22 15:42:35 2009
Although it is very effective for low-level threading, but the thread module is very limited compared to the newer
threading module.
The Threading Module:
The newer threading module included with Python 2.4 provides much more powerful, high-level support for
threads than the thread module discussed in the previous section.
The threading module exposes all the methods of the thread module and provides some additional methods:
• threading.activeCount(): Returns the number of thread objects that are active.
• threading.currentThread(): Returns the number of thread objects in the caller's thread control.
• threading.enumerate(): Returns a list of all thread objects that are currently active.
In addition to the methods, the threading module has the Thread class that implements threading.
The methods provided by the Thread class are as follows:
• run(): The run() method is the entry point for a thread.
• start(): The start() method starts a thread by calling the run method.
• join([time]): The join() waits for threads to terminate.
• isAlive(): The isAlive() method checks whether a thread is still executing.
• getName(): The getName() method returns the name of a thread.
• setName(): The setName() method sets the name of a thread.
Creating Thread using Threading Module:
To implement a new thread using the threading module, you have to do the following:
• Define a new subclass of the Thread class.
• Override the __init__(self [,args]) method to add additional arguments.
TUTORIALS POINT
Simply Easy Learning