Python Tutorial

Showing posts with label Thread. Show all posts
Showing posts with label Thread. Show all posts

Thursday, June 7, 2012

Access shared resource

Sometime we need to access shared document, for example when our application write to a single file on multi-thread. In this case we need to access the through locking.

This technique is useful for web crawler.
lock=threading.Lock()
def writeToFile():
    lock.acquire()
    try:
        //write data
    finally:
        lock.release()

Thursday, October 28, 2010

Python Threading Use A Thread Class

 '''
    This code use a thread class
    - Save this class named 'AnyName.py'
 - Run this code you need class 'ThreadClass.py'
'''
import ThreadClass

for i in range(1,4):
    threadObject=ThreadClass.ThreadClass(i)
    threadObject.start()



Output:
output:  output: 1output:  
 23

output:  1
output:  2output: 
 3
output:  1
output: output:   32

Python Threading

'''
    This code use python threading syntax
    - Save this class named 'ThreadClass.py'
'''
import threading
import time

class ThreadClass(threading.Thread):
    def __init__(self,data):
        threading.Thread.__init__(self)
        self.data=data
        
    def run(self):
        for i in range(0,3):
            print "output: ",self.data
            time.sleep(1);