2
votes

I need a C equivalent of the following Java class. It is a queue lock known as an Anderson Lock used in thread synchronization. I am not comfortable using C, and there are some thread classes which I don't really know how to use. thanks.

I am using OpenSolaris.

public class ALock implements Lock {
     ThreadLocal mySlotIndex = new       
     ThreadLocal (){
          protected Integer initialValue() {
               return 0;
          }
     };
     AtomicInteger tail;
     boolean[] flag;
     int size;
     public ALock(int capacity) {
          size = capacity;
          tail = new AtomicInteger(0);
          flag = new boolean[capacity];
          flag[0] = true;
     }
     public void lock() {
          int slot = tail.getAndIncrement() % size;
          mySlotIndex.set(slot);
          while (! flag[slot]) {};
     }
     public void unlock() {
          int slot = mySlotIndex.get();
          flag[slot] = false;
          flag[(slot + 1) % size] = true;
     }
}
1

1 Answers

1
votes

I assume you're referring to the type of spin lock described in this paper: http://homes.cs.washington.edu/~tom/pubs/spinlock.pdf

This kind of lock is used for performance reasons. It is efficient because each of the cores spins on a separate address, which remains local to its cache. This reduces "snooping" cache traffic between cores.

However, when implementing this in C and then calling it from Java, the performance advantages are difficult for me to see..

In any case, the concurrencykit site provides C implementations of a number of different kinds of spinlocks and other concurrency related things:

http://concurrencykit.org/index.html

This page has the documentation for the anderson type of spinlock: http://concurrencykit.org/doc/ck_spinlock.html