Page 1 of 1
SaveJSON()
Posted: Wed Jun 19, 2024 10:58 pm
by idle
does SaveJSON lock the file for concurrent writes or do I have to lock the file myself?
Re: SaveJSON()
Posted: Thu Jun 20, 2024 8:37 am
by PBJim
If it's any help Idle, I had the same question when I developed a multi-user application that services requests to save JSON data. I carried out some tests by writing from multiple threads and I found that if another thread was in the process of writing the same JSON file, then the Else clause was performed. I think the answer therefore is that it's a lock, with the Else being executed.
This is the test below — just a loop. I'm sure the developers can confirm more detail, but thought these results might be of relevance.
Code: Select all
If SaveJSON(testno.i, filename.s)
Else
; List not saved
EndIf
List saved as file "test" records 1
List not saved
List saved as file "test" records 1
List not saved
List not saved
List saved as file "test" records 1
List not saved
List saved as file "test" records 1
List saved as file "test" records 1
List not saved
List saved as file "test" records 1
Re: SaveJSON()
Posted: Thu Jun 20, 2024 10:50 am
by idle
Thanks PBjim, that looks encouraging.
Re: SaveJSON()
Posted: Thu Jun 20, 2024 11:16 am
by PBJim
Yes, it's pretty robust. I was more concerned that the app might crash, but it didn't. I ran four threads, each 100,000 loop iterations, attempting to write to the same file.
The only thing is, if you absolutely need to create the file, it's necessary to wrap it inside a re-try loop, which then makes the code seem a bit over-engineered, just for the sake of writing a file.
Re: SaveJSON()
Posted: Thu Jun 20, 2024 11:27 am
by jacdelad
Use a mutex to queue the write operations.
Re: SaveJSON()
Posted: Thu Jun 20, 2024 11:44 am
by idle
PBJim wrote: Thu Jun 20, 2024 11:16 am
Yes, it's pretty robust. I was more concerned that the app might crash, but it didn't. I ran four threads, each 100,000 loop iterations, attempting to write to the same file.
The only thing is, if you absolutely need to create the file, it's necessary to wrap it inside a re-try loop, which then makes the code seem a bit over-engineered, just for the sake of writing a file.
I'm defiantly guilty of over engineering. I also need to protect the file across processes. I'm using a lock file for that but haven't' tested it yet.
Re: SaveJSON()
Posted: Thu Jun 20, 2024 12:56 pm
by freak
The file is opened with FILE_SHARE_READ mode only so it cannot be opened for writing at the same time but it can be read.
Re: SaveJSON()
Posted: Thu Jun 20, 2024 9:33 pm
by idle
Great

thanks