[PD] object using a thread?

Christian Klippel ck at mamalala.de
Sun Aug 28 19:32:56 CEST 2005


hi olaf,

Am Sonntag 28 August 2005 18:49 schrieb Olaf Matthes:
> Christian Klippel wrote:
> > after all, i dont need any lock.
> > the thread only reads the usb bus with a really high timeout value.
> > it then fills one side of a double_buffer, while the other side is read
> > by the metro-like tick in the ps object.
> > if that reading buffer is empty, the thread will switch the buffers,
> > thats all. no pd functions involved in the thread.
>
> But you still need locks! When you write data to a buffer you should
> lock the buffer (or if there are two of them, lock the variable that
> indicates which one is currently used). Also do so when reading from the
> buffer, or you'll get sooner or later hard to reproduce crashes...
>

for now, it looks that way:
at the thread, at the very beginning of each iteration:

if(buf_count[whichbuf] <= 0)  // check if the read buffer is empty
{
  mybuf = whichbuf;   // if so, use it for writing
  whichbuf = !(whichbuf &1);  // and toggle the read buffer
}

where mybuf is a local variable of the thread.

and at the buffer reading function outside the thred:

if(buf_count[whichbuf] > 0)
{
    .....
    buf_count[whichbuf] = 0;
}

that means, all the switching is done inside the thread, and _only_ if there 
is an actual switch happen, that is just one line of code. and the switch 
_only_ occurs if the reading buffer (for read outside the thread) is empty, 
and thus not accessed.

the reading outside the thread is done only if that buffer is filled. at the 
very same time the thread would not switch that variable, since it is still 
full. it gets reset to 0 only if all processing is done and no further 
accesses will happen.

so far nothing bad happens in the test program i did (not a pd object right 
now). not if the read stuff gets called very fast (10 µS intervall) nor with 
very long intervalls (>1 second) and all inbetween.
( the (ugly) test code is at http://mamalala.de/thread_test.c )

do you think it makes sense here to lock anything? so far i cant see a need, 
but educate me if im wrong, please ;-) im just trying to avoid locking when 
possible.....

> Olaf
>

greets,

chris





More information about the Pd-list mailing list