473,320 Members | 2,147 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,320 software developers and data experts.

Using control characters to break out of threads

I am working on a program that uses two threads to Read and Write to a serial port. I am able to use ^C to break out of the main thread, but the two worker threads still run. Is there any method that I can use where my threads will detect a ^C and kill themselves, or something to that regard?
May 16 '07 #1
7 1877
Here is the code that I am working with:


Expand|Select|Wrap|Line Numbers
  1.  
  2. import threading, serial
  3.  
  4. class TxThread(threading.Thread):
  5.     """
  6.     Serial Tx Thread Class
  7.     """
  8.  
  9.     def __init__(self, sp, lock):
  10.         """
  11.         Constructor, setting initial variables
  12.         """
  13.         self._stopevent = threading.Event()
  14.         self._sleeptime = 0.25
  15.         self._txcount = 0
  16.         self._lock = lock
  17.         self._port = sp
  18.  
  19.         threading.Thread.__init__(self, name="TxThread")
  20.  
  21.     def run(self):
  22.         """
  23.         overload of threading.thread.run()
  24.         main control loop
  25.         """
  26.         while not self._stopevent.isSet():
  27.             self._lock.acquire()
  28.             self._port.write("Python Threading\n")
  29.             self._txcount = self._txcount + 1
  30.             print "Tx Frames: " + str(self._txcount)
  31.             self._port.flushOutput()
  32.             self._stopevent.wait(self._sleeptime)
  33.             self._lock.notifyAll()
  34.             self._lock.release()
  35.  
  36.         def join(self, timeout=None):
  37.             """
  38.             Stop the thread
  39.             """
  40.             self._stopevent.set()
  41.             threading.Thread.join(self, timeout)
  42.  
  43.  
  44.  
  45. class RxThread(threading.Thread):
  46.     """
  47.     Serial Rx Thread Class
  48.     """
  49.     def __init__(self, sp, lock):
  50.         """
  51.         Constructor, setting initial values
  52.         """
  53.         self._stopevent = threading.Event()
  54.         self._sleeptime = 0.25
  55.         self._rxcount = 0
  56.         self._lock = lock
  57.         self._port = sp
  58.  
  59.         threading.Thread.__init__(self, name="RxThread")
  60.  
  61.     def run(self):
  62.         """
  63.         overload of threading.thread.run()
  64.         main control loop
  65.         """
  66.  
  67.         while not self._stopevent.isSet():
  68.             self._lock.acquire()
  69.             readport = self._port.readlines()
  70.             self._rxcount = self._rxcount + 1
  71.             print "Rx Frames: " + str(self._rxcount) + " Data: " + str(readport)
  72.             self._port.flushInput()
  73.             self._stopevent.wait(self._sleeptime)
  74.             self._lock.release()
  75.  
  76.     def join(self, timeout=None):
  77.             """
  78.             Stop the thread
  79.             """
  80.             self._stopevent.set()
  81.             threading.Thread.join(self, timeout)
  82.  
  83. def main():
  84.  
  85.     port = serial.Serial("/dev/ttyUSB0", 19200, timeout=1)
  86.     lock = threading.Condition()
  87.  
  88.     tx = TxThread(port, lock)
  89.     rx = RxThread(port, lock)
  90.  
  91.     rx.run()
  92.     tx.run()
  93.  
  94.     rx.join()
  95.     tx.join()
  96.  
  97. if __name__ == "__main__":
  98.     main()
  99.  
  100.  
May 16 '07 #2
bartonc
6,596 Expert 4TB
I am working on a program that uses two threads to Read and Write to a serial port. I am able to use ^C to break out of the main thread, but the two worker threads still run. Is there any method that I can use where my threads will detect a ^C and kill themselves, or something to that regard?
I alway use a threading.Event. Spawned threads loop on
Expand|Select|Wrap|Line Numbers
  1. while self.runEvent.isSet():
The main thread then calls
Expand|Select|Wrap|Line Numbers
  1. theEventISentToSpawnedThread.clear()
before it exits.

Hope that helps.
May 17 '07 #3
Yes, The code above does exit the thread on a ^C, but it starves the transmit thread. My main problem is preventing that starvation.
May 23 '07 #4
bartonc
6,596 Expert 4TB
Yes, The code above does exit the thread on a ^C, but it starves the transmit thread. My main problem is preventing that starvation.
I've posted my GPS model class here. I spent a long time getting an OS read() to finish before the thread terminated (which it wouldn't do if read() was still waiting for the next packet).
May 24 '07 #5
Finaly got the threading portion correct, and now have my read and write processes running simultaneously. However I am coming into a problem when I use a function inside of the thread, and I cannot determine what the problem is. See the following code:

Expand|Select|Wrap|Line Numbers
  1. def Reader(port, lock, bertpat):
  2.     """
  3.     Reads data off the serial port
  4.     """
  5.     frames = 0
  6.     print "in read"
  7.     try:
  8.         while 1:
  9.             print "in while"
  10.             lock.acquire()
  11.             print "in lock"
  12.  
  13.             while a.inWaiting() < 511: print "waiting"
  14.                         #Breaks executing the preceding line
  15.  
  16.  
  17.             a = port.readline()
  18.             lock.release()
  19.  
  20.             if str(a) == str(bertpat + "\n"):
  21.                 frames = incCount(frames)
  22.                 print "RxFrames " + str(frames)
  23.             else:
  24.                 print "Data Bad\n" + a + "\n" + bertpat
  25.  
  26.             time.sleep(0.1)
  27.  
  28.     except KeyboardException:
  29.         pass
Jun 7 '07 #6
bartonc
6,596 Expert 4TB
Finaly got the threading portion correct, and now have my read and write processes running simultaneously. However I am coming into a problem when I use a function inside of the thread, and I cannot determine what the problem is. See the following code:

Expand|Select|Wrap|Line Numbers
  1.             while a.inWaiting() < 511: print "waiting"
  2.                         #Breaks executing the preceding line
  3.  
  4. ##############
  5.  
  6.     except KeyboardException:
  7.         pass
1. a is undefined. What object are you expecting to have the inWaiting() function?

2. Change pass to break will break out of the thread.


PS: Sorry that my Windows threading example was probably not much help. I see, now, that you are on Ubuntu.
Jun 7 '07 #7
bartonc
6,596 Expert 4TB
2. Change pass to break will break out of the thread.
I take that back. Only the main thread will see the KeyboardInterupt.
Jun 7 '07 #8

Sign in to post your reply or Sign up for a free account.

Similar topics

3
by: rh0dium | last post by:
Hi all, Another newbie question. So you can't use signals on threads but you can use select. The reason I want to do this in the first place it I need a timeout. Fundamentally I want to run a...
1
by: Sori Schwimmer | last post by:
Hi, I am working on an application which involves interprocess communication. More to the point, processes should be able to notify other processes about certain situations, so the "notifyees"...
5
by: Miyra | last post by:
Hi. I'm working with an app that uses exceptions for control flow. These are code blocks where exceptions are thrown/caught regularly. A couple hundred exceptions occur per hour and they're caught...
1
by: j | last post by:
Hi, I've been trying to do line/character counts on documents that are being uploaded. As well as the "counting" I also have to remove certain sections from the file. So, firstly I was working...
11
by: BoloBaby | last post by:
OK, check this out... I have a form with a panel control and button on it (outside the panel control). I have two event handlers - one handles the click event of the button on the form. The...
2
by: David | last post by:
Hi, Could PHP be used to take a txt file (or set of txt files) and add a string of characters every X number of words or characters? Say a txt file with 50,000 characters/5,000 words how would...
1
by: kommaraju | last post by:
iam a starter to db2 & jdbc.i have a servlet program which connects to ibm db2 using jdbc.when i run this using apache tomcat 4.1.34 , it is showing a error message of HTTP STATUS 500 my jdbc...
1
by: kommaraju | last post by:
iam a starter to db2 & jdbc.i have a servlet program which connects to ibm db2 using jdbc.when i run this using apache tomcat 4.1.34 , it is showing a error message of HTTP STATUS 500 my jdbc...
22
by: John | last post by:
Hi Folks, I'm experimenting a little with creating a custom CEdit control so that I can decide on what the user is allowed to type into the control. I started off only allowing floating point...
0
by: DolphinDB | last post by:
The formulas of 101 quantitative trading alphas used by WorldQuant were presented in the paper 101 Formulaic Alphas. However, some formulas are complex, leading to challenges in calculation. Take...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
0
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.