简体   繁体   中英

a generic lock-free synchronization

The implementation of lock-free data structures is sometimes not easy to implement. The following approach may seem generic and easy but I think here we have some issues:

private AtomicBoolean lock = new AtomicBoolean(false);

    public void func(...) {
        while !lock.compareAndSet(false,true);
        // Some code goes here...
        ...
        ...
        ...
        lock.set(false); 
    }
}

I think The code above is not really "lock-free", as it locks the awaiting Threads in the while loop in busy-wait mode.

Therefore, the code is suitable only when the "right" lock-free synchronization is impossible.

My question is - Is it possible to implement a generic lock-free with some different approach and it will works so threads will not be in blocked(like synchronized) or busy mode state and the code will run parallel, so we improve performance?

My aim is to keep the threads running. I know that if the code is long, it is better to use the synchronized mechanism instead of the lock-free implementation, so let's assume we are talking on short code.

For example, below is example of Linkedlist which I think is good approach but it not generic for common data stractures. if we are used here with AtomicBoolean as I show above, it will not be realy "lock-free".

public class LinkedList<T> {

    private AtomicReference<Link<T>> head = new AtomicReference(null);

    public  void add(T data) {
      Link<T> localHead;
      Link<T> newHead = new Link<>(null, data);

      do {
        localHead = head.get();
        newHead.next = localHead;        
      } while (!head.compareAndSet(localHead, newHead));
    }
}

There are indeed universal construction schemes for lock-free or even wait-free algorithms. For example:

However, these are usually more interesting from a theoretical perspective rather than a practical one. In practice, specialized lock-free algorithms usually perform better than those derived from these universal constructions.

If you are interesting in the area of lock-free programming I would recommend to start with the book The Art of Multiprocessor Programming .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM