Showing posts with label multithreading. Show all posts
Showing posts with label multithreading. Show all posts

Tuesday, May 3, 2011

How to synchronize threads using locks

In this post we will extend a previous example about multithreading. Here's how to synchronize two threads using a simple lock:
import threading
import thread
import time

class MyThread(threading.Thread):
 def __init__(self, myName, lock):
  threading.Thread.__init__(self)
  self.myName = myName
  self.lock = lock

 def run(self):
  while True:
   self.lock.acquire()
   print self.myName,'is in the critical section the lock'
   time.sleep(1) # wait 1 second
   print self.myName,'releasing the lock'
   self.lock.release()
   

if __name__=="__main__":
 lock=thread.allocate_lock()
 thread1 = MyThread("1",lock)
 thread1.start()
 thread2 = MyThread("2",lock)
 thread2.start()
 while True: pass
A thread can't print in the console until he acquires the lock. The output will be similar to this:
1 is in the critical section the lock
1 releasing the lock
2 is in the critical section the lock
2 releasing the lock
1 is in the critical section the lock
1 releasing the lock
2 is in the critical section the lock
2 releasing the lock
2 is in the critical section the lock
2 releasing the lock
1 is in the critical section the lock
1 releasing the lock
2 is in the critical section the lock
2 releasing the lock
...
WARNING: This is a simple example with two threads and only one critical section, more complicated situation need other synchronization mechanisms.

Friday, April 22, 2011

How to implement a multithread echo server

The example implement a multithread echo server. Every incoming request is handed off to a worker thread that will process the request.
import socket
import thread

def handle(client_socket, address):
 while True:
  data = client_socket.recv(512)
  if data.startswith("exit"): # if data start with "exit"
   client_socket.close() # close the connection with the client
   break
  client_socket.send(data) # echo the received string

# opening the port 1075
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind((socket.gethostname(),1075))
server.listen(2)

while True: # listen for incoming connections
 client_socket, address = server.accept()
 print "request from the ip",address[0]
 # spawn a new thread that run the function handle()
 thread.start_new_thread(handle, (client_socket, address)) 
And now we can use telnet to communicate with the server application:
$ telnet localhost 1075
Trying ::1...
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
hi
hi
echo this!
echo this!
exit
Connection closed by foreign host.

Wednesday, April 20, 2011

How to create threads

The example show how to define the behavior of a thread and run it.
import threading
import time
import random

class MyThread(threading.Thread):
 def __init__(self, myName):
  threading.Thread.__init__(self)
  self.myName = myName

 def run(self):
  while True:
   time.sleep(random.randint(0,3)) # wait a random time from 0 to 3 secs
   print "My name is",self.myName

thread1 = MyThread("1")
thread1.start() # the thread will run in background
thread2 = MyThread("2")
thread2.start()
My name is 1
My name is 1
My name is 2
My name is 2
My name is 1
...
The two threads will print in the console their attribute myName with random time interval.