Re: select() and multi-threading




Robert Latest wrote:
I'm writing an app that does some writing to and reading from an
external device. Since I don't know when data comes in, I'd like to do
the reading in a separate thread which accumulates data in a queue to be
processed by the main application whan it has time.

I've got this working now, but the reading and writing of the file
descriptor is in no way synchronized -- the "listener" thread simply
blocks on a read() until some data comes in, then puts it in the queue.

My hunch is that this will eventualy break because of a collision of a
read() and write() from the two threads.

Question 1: Can it?

On the assumption that it can, I thought about letting the "listener"
block on a select() on the fd, lock a mutex when select() returns, do
the read() and unlock the mutex when finished. Of course the write() in
the other thread is protected by the same mutex.

Question 2: Is this safe, or are there still collisions possible
(between write() and select())?

This question has been answered recently here
http://groups.google.com/group/comp.os.linux.networking/msg/da8c7a03acfa1d18
(show option -> view thread)

Question 3: How would you do it?

Learn more about IO strategies
http://www.kegel.com/c10k.html#strategies
Use nonblocking IO. Do reading and writing in the same thread.

.



Relevant Pages

  • Re: Read from and Write to the same socket from two threads
    ... Do I have to put a lock such as mutex to prevent ... reading and writing from happening concurrently? ... Charles Zhang ...
    (microsoft.public.win32.programmer.networks)
  • RE: pthread_mutex_unlock (was Re: sched_yield() makes OpenLDAP slow)
    ... >> reading of it incredibly strained for the three reasons I stated. ... > You have essentially created a tri-state mutex. ... thread waiting for the mutex is woken (but not necessarily guaranteed the ...
    (Linux-Kernel)
  • select() and multi-threading
    ... I'm writing an app that does some writing to and reading from an ... the reading in a separate thread which accumulates data in a queue to be ... My hunch is that this will eventualy break because of a collision of a ... the readand unlock the mutex when finished. ...
    (comp.unix.programmer)
  • Re: [PATCH 0/6] Clean up the sdio_uart driver and fix the tty code
    ... some process is reading from the device. ... This used to behave well ... The claim method takes the mutex, checks if it is NULL and acts ...
    (Linux-Kernel)
  • Re: File access from different processes
    ... it should not matter (you don't need the mutex). ... long as you're not reading from the same location as the write. ... If the file pointer belongs to the file handle and I'm ...
    (microsoft.public.windowsce.platbuilder)

Loading