[ILUG] Test-and-set in C/C++

P at draigBrady.com P at draigBrady.com
Fri Oct 1 11:03:23 IST 2004


Vincent Cunniffe wrote:
> Hi,
> 
> I've been unable to find any way of doing a proper test-and-set command 
> in C/C++... anyone know a way of doing this?
> 
> This is going to be executed in a signal, possibly re-entrant, so it 
> can't be wrapped in a semaphore, mutex, or anything else : it has to be 
> a single, atomic, test-and-set operation which cannot possibly be 
> interrupted or pre-empted. This is also executing in a threaded 
> environment.
> 
> I've seen various pieces of sample code stupidly claiming to be test and 
> set, such as 'if (i==0) {i++; return true;}', but haven't found anything 
> which is basically an exposure of the underlying atomic hardware 
> instruction.
> 
> Vin

#include <asm/bitops.h> //to get the following

static __inline__ int test_and_set_bit(int nr, volatile void * addr)
{
         int oldbit;
 

         __asm__ __volatile__(
                 "btsl %2,%1\n\tsbbl %0,%0"
                 :"=r" (oldbit),"=m" (ADDR)
                 :"Ir" (nr) : "memory");
         return oldbit;
}

There is also a non atomic (volatile) version there for comparison.

-- 
Pádraig Brady - http://www.pixelbeat.org
--- Following generated by rotagator ---

To setup terminal application foreground colours
appropriate for a dark background:

ls
     cp /etc/DIR_COLORS ~/.dircolors
vim
     echo "set background=dark" >> ~/.vimrc

Note to change colours for linux virtual terminals
     setterm -background white -foreground black -store
--



More information about the ILUG mailing list