chatprogramm was sonst
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

57 lines
1.8 KiB

1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
  1. package server.util;
  2. /*
  3. !!! WORK IN PROGRESS !!!
  4. trying to implement a wait-free queue
  5. */
  6. import java.util.concurrent.atomic.AtomicInteger;
  7. import java.util.concurrent.atomic.AtomicMarkableReference;
  8. import java.util.concurrent.atomic.AtomicReferenceArray;
  9. public class Queue<T> {
  10. private AtomicMarkableReference<Integer> head, tail;
  11. private final int capacity;
  12. private AtomicReferenceArray<T> items;
  13. public Queue(int capacity) {
  14. this.capacity = capacity;
  15. this.head = new AtomicMarkableReference(0, false);
  16. this.tail = new AtomicMarkableReference(0, false);
  17. items = new AtomicReferenceArray<T>(capacity);
  18. }
  19. public boolean enq(T x) {
  20. boolean[] mark = new boolean[1];
  21. if (tail.get(mark) - head.get(mark) == capacity) return false;
  22. int tmp;
  23. do {
  24. tmp = tail.get(mark);
  25. System.out.println("enq: " + x);
  26. System.out.println("val tmp: " + tmp);
  27. System.out.println("val tmp: " + next(tmp));
  28. items.compareAndSet(tmp, null, x);
  29. } while (tail.compareAndSet(tmp, next(tmp), true, false));
  30. System.out.println("head: " + head.getReference() + "\ntail: " + tail.getReference() + "\ndiff: " + (tail.getReference() - head.getReference()));
  31. return true;
  32. }
  33. public T deq() {
  34. boolean[] mark = new boolean[1];
  35. System.out.println("test: " + (tail.get(mark) - head.get(mark)) + "\ncap: " + capacity);
  36. if (tail.get(mark) - head.get(mark) == 0) return null;
  37. int tmp;
  38. T x;
  39. do {
  40. tmp = head.get(mark);
  41. System.out.println("head: " + next(tmp));
  42. x = items.getAndSet(tmp, null);
  43. } while (head.compareAndSet(tmp, next(tmp), false, true));
  44. return x;
  45. }
  46. private int next(int x) {
  47. return (x + 1) % capacity;
  48. }
  49. }