Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Try to fix race condition in Hotswap example #3885

Merged
merged 1 commit into from
Nov 23, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 11 additions & 14 deletions docs/std/hotswap.md
Original file line number Diff line number Diff line change
Expand Up @@ -37,28 +37,25 @@ def rotating(n: Int): Resource[IO, Logger[IO]] =
for {
index <- Ref[IO].of(0)
count <- Ref[IO].of(0)
//Open the initial log file
f <- hs.swap(file("0.log"))
logFile <- Ref[IO].of(f)
// Open the initial log file
_ <- hs.swap(file("0.log"))
} yield new Logger[IO] {
def log(msg: String): IO[Unit] =
count.get.flatMap { currentCount =>
if (msg.length() < n - currentCount)
for {
currentFile <- logFile.get
_ <- write(currentFile, msg)
_ <- count.update(_ + msg.length())
} yield ()
hs.get.use { currentFile =>
write(currentFile, msg) *>
count.update(_ + msg.length())
}
else
for {
//Reset the log length counter
// Reset the log length counter
_ <- count.set(msg.length())
//Increment the counter for the log file name
// Increment the counter for the log file name
idx <- index.updateAndGet(_ + 1)
//Close the old log file and open the new one
f <- hs.swap(file(s"$idx.log"))
_ <- logFile.set(f)
_ <- write(f, msg)
// Close the old log file and open the new one
_ <- hs.swap(file(s"$idx.log"))
_ <- hs.get.use(write(_, msg))
Comment on lines +57 to +58
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There's still a race condition here with the counter and the swapping /shrug

} yield ()
}
}
Expand Down
Loading