Posted tagged ‘serial port’

Threads in python: a short way

August 8, 2008

Today i was in a meeting with some students/workers who needs to program an application for control devices through a serial port, well in this moment i will not take about this task, if not about the need of send many independent signals.
In fact, currently the application (with a curses module) only controls a single device, but we need operates “n” ports and “n” boards, who we can that?. Simple: threads.
Threads allow send tasks simultaneously in a program, each task or thread is independent and helps to “do” many things in the same time. Well, stop to the words:

#!/usr/bin/env python

import thread
import time

def print_time(delay):
    while 1:
    time.sleep(delay)
    print time.ctime(time.time())

for a in range(0,20):
    thread.start_new_thread(print_time,(2,))
    print “Task:”,a
    time.sleep(2)

Obviously, copy the code and paste on a new file, by example: thread_demo.py, run it.

Task: 0
Fri Aug 8 21:50:28 2008
Task: 1
Fri Aug 8 21:50:30 2008
Fri Aug 8 21:50:30 2008
Task: 2
Fri Aug 8 21:50:32 2008
Fri Aug 8 21:50:32 2008
Fri Aug 8 21:50:32 2008
Task: 3
Fri Aug 8 21:50:34 2008
Fri Aug 8 21:50:34 2008
Fri Aug 8 21:50:34 2008
Fri Aug 8 21:50:34 2008
…..

The result show us in a same time many tasks, try to apply this concept to any application which needs include parallel works. In the further articles i will to try to focus in some complex python areas, obviously, i will not forget the serial port control (or parallel, USB, etc. if you wish).

Advertisements