Skip to content

Commit

Permalink
use atomic bool
Browse files Browse the repository at this point in the history
  • Loading branch information
an-prata committed Oct 13, 2023
1 parent b628d34 commit eb0cb35
Showing 1 changed file with 7 additions and 5 deletions.
12 changes: 7 additions & 5 deletions src/main/java/frc/robot/subsystems/WriteLock.java
Original file line number Diff line number Diff line change
@@ -1,13 +1,15 @@
package frc.robot.subsystems;

import java.util.concurrent.atomic.AtomicBoolean;

/**
* A write lock to prevent race conditions. This lock does not actually
* guarantee the memory safety of the contained object, each method call
* requres that the programmer make a "promise" to follow its rules.
*/
public class WriteLock<T> {
private T obj;
private boolean locked;
private AtomicBoolean locked;

/**
* Creates a new lock around the given object. The given object mey not be used
Expand All @@ -22,16 +24,16 @@ public WriteLock(T obj) {
* Blockes the current thread until the object is made available.
*/
public T lock() {
while (locked == true) {}
locked = true;
while (locked.get()) {}
locked.set(true);
return obj;
}

/**
* Unocks the object, it should not be used after this call.
*/
public void unlock() {
locked = false;
locked.set(false);
}

/**
Expand All @@ -40,6 +42,6 @@ public void unlock() {
*/
public void unlock(T obj) {
this.obj = obj;
locked = false;
locked.set(false);
}
}

0 comments on commit eb0cb35

Please sign in to comment.