#151 Serial.write() without a timeout uses 100% CPU on POSIX

v2.7
closed-fixed
linux speed (1)
5
2013-10-12
2013-07-04
Jim Paris
No

On POSIX, this program takes approximately 100% CPU:

import serial
s = serial.Serial("/dev/ttyS0", 9600)
while True:
    s.write('hello, world\n')

This program takes approximately 0% CPU:

import serial
s = serial.Serial("/dev/ttyS0", 9600)
s.setWriteTimeout(1000000)
while True:
    s.write('hello, world\n')

The reason is because the fd is nonblocking and Serial.write() spins
in a tight loop calling os.write(). With a timeout, it waits for the
fd to become ready with select(). It needs to do that in the case
where there's not a timeout, too.

-jim

Index: pyserial/serial/serialposix.py
===================================================================
--- pyserial/serial/serialposix.py  (revision 460)
+++ pyserial/serial/serialposix.py  (working copy)
@@ -497,6 +497,10 @@
                     _, ready, _ = select.select([], [self.fd], [], timeleft)
                     if not ready:
                         raise writeTimeoutError
+                else:
+                    _, ready, _ = select.select([], [self.fd], [], None)
+                    if not ready:
+                        raise SerialException('write failed')
                 d = d[n:]
                 t = t - n
             except OSError, v:

Discussion

  • Chris Liechti

    Chris Liechti - 2013-10-12
    • status: open --> closed-fixed
    • assigned_to: Chris Liechti
    • Group: v1.0 (example) --> v2.7
     
  • Chris Liechti

    Chris Liechti - 2013-10-12

    Thanks, committed for v2.7.

     

Log in to post a comment.

Get latest updates about Open Source Projects, Conferences and News.

Sign up for the SourceForge newsletter:

JavaScript is required for this form.





No, thanks