1

I have an actix-based API, that operates entirely async. There is one endpoint, that writes a file with a user-given filename on the filesystem (I use async-std library for async fs-operations).

My problem now is, that I run into race-conditions whenever two calls are modifying the same file. I do not want a "global" mutex that locks on each single write, because that would artificially slow down my application for no reason.

Is there a possibility to acquire a lock for each single file, in order that only write-operations for this one specific file are locked & unlocked?

Piwo
  • 1,347
  • 1
  • 12
  • 19
  • You could have a global `HashMap>` that you use to synchronize access to the file. The hashmap itself would probably need to be in a `RwLock` which you write to only when you add a new entry to the hashmap. – user4815162342 Dec 13 '21 at 09:42
  • "I do not want a "global" mutex that locks on each single write, because that would artificially slow down my application for no reason." how artificially ? that normal if you need to mutate a state. – Stargateur Dec 13 '21 at 09:51
  • A global Hashmap containing mutexes could be a solution, I will try this out. @Stargateur I could answer this best by an example: Image there are very many calls on a file called "a.txt" queued up. In between there comes one call to write into "b.txt". Why should "b.txt" be waiting until the lock for "a.txt" is free? – Piwo Dec 13 '21 at 10:01
  • you obviously need a mutex by file anyway at this point, use a "true" database – Stargateur Dec 13 '21 at 10:24

0 Answers0