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?
7 1877
Here is the code that I am working with: -
-
import threading, serial
-
-
class TxThread(threading.Thread):
-
"""
-
Serial Tx Thread Class
-
"""
-
-
def __init__(self, sp, lock):
-
"""
-
Constructor, setting initial variables
-
"""
-
self._stopevent = threading.Event()
-
self._sleeptime = 0.25
-
self._txcount = 0
-
self._lock = lock
-
self._port = sp
-
-
threading.Thread.__init__(self, name="TxThread")
-
-
def run(self):
-
"""
-
overload of threading.thread.run()
-
main control loop
-
"""
-
while not self._stopevent.isSet():
-
self._lock.acquire()
-
self._port.write("Python Threading\n")
-
self._txcount = self._txcount + 1
-
print "Tx Frames: " + str(self._txcount)
-
self._port.flushOutput()
-
self._stopevent.wait(self._sleeptime)
-
self._lock.notifyAll()
-
self._lock.release()
-
-
def join(self, timeout=None):
-
"""
-
Stop the thread
-
"""
-
self._stopevent.set()
-
threading.Thread.join(self, timeout)
-
-
-
-
class RxThread(threading.Thread):
-
"""
-
Serial Rx Thread Class
-
"""
-
def __init__(self, sp, lock):
-
"""
-
Constructor, setting initial values
-
"""
-
self._stopevent = threading.Event()
-
self._sleeptime = 0.25
-
self._rxcount = 0
-
self._lock = lock
-
self._port = sp
-
-
threading.Thread.__init__(self, name="RxThread")
-
-
def run(self):
-
"""
-
overload of threading.thread.run()
-
main control loop
-
"""
-
-
while not self._stopevent.isSet():
-
self._lock.acquire()
-
readport = self._port.readlines()
-
self._rxcount = self._rxcount + 1
-
print "Rx Frames: " + str(self._rxcount) + " Data: " + str(readport)
-
self._port.flushInput()
-
self._stopevent.wait(self._sleeptime)
-
self._lock.release()
-
-
def join(self, timeout=None):
-
"""
-
Stop the thread
-
"""
-
self._stopevent.set()
-
threading.Thread.join(self, timeout)
-
-
def main():
-
-
port = serial.Serial("/dev/ttyUSB0", 19200, timeout=1)
-
lock = threading.Condition()
-
-
tx = TxThread(port, lock)
-
rx = RxThread(port, lock)
-
-
rx.run()
-
tx.run()
-
-
rx.join()
-
tx.join()
-
-
if __name__ == "__main__":
-
main()
-
-
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 - while self.runEvent.isSet():
The main thread then calls - theEventISentToSpawnedThread.clear()
before it exits.
Hope that helps.
Yes, The code above does exit the thread on a ^C, but it starves the transmit thread. My main problem is preventing that starvation.
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).
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: - def Reader(port, lock, bertpat):
-
"""
-
Reads data off the serial port
-
"""
-
frames = 0
-
print "in read"
-
try:
-
while 1:
-
print "in while"
-
lock.acquire()
-
print "in lock"
-
-
while a.inWaiting() < 511: print "waiting"
-
#Breaks executing the preceding line
-
-
-
a = port.readline()
-
lock.release()
-
-
if str(a) == str(bertpat + "\n"):
-
frames = incCount(frames)
-
print "RxFrames " + str(frames)
-
else:
-
print "Data Bad\n" + a + "\n" + bertpat
-
-
time.sleep(0.1)
-
-
except KeyboardException:
-
pass
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: -
while a.inWaiting() < 511: print "waiting"
-
#Breaks executing the preceding line
-
-
##############
-
-
except KeyboardException:
-
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.
2. Change pass to break will break out of the thread.
I take that back. Only the main thread will see the KeyboardInterupt.
Sign in to post your reply or Sign up for a free account.
Similar topics
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...
|
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"...
|
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...
|
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...
|
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...
|
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...
|
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...
|
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...
|
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...
|
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...
|
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...
|
by: ryjfgjl |
last post by:
ExcelToDatabase: batch import excel into database automatically...
|
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...
|
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...
|
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)...
|
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...
|
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....
|
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
| |