[fpc-pascal] Is System.IOResult thread-safe? (If not, I need to replace it.)
Cox, Stuart TRAN:EX
Stuart.Cox at gov.bc.ca
Fri Nov 19 23:02:11 CET 2010
Thanks for this example, Jonas.
Stu Cox
On 10 Nov 2010, at 13:26, MegaBrutal wrote:
> I'm new on the list. I have a problem. I've been trying to make my
> application thread-safe by using lockfiles. I used System.Rewrite to
> lock the file, and System.IOResult to check the result. But I've
> encountered problems, and such problems are most likely occur, when
> more than one thread's trying to lock the file at the same time. I've
> been thinking what might be the problem, and I wondered if
> System.IOResult is thread-safe or not. I suppose not. :(
It is thread safe, but your function is not.
> Not a big
> deal, though, I may use an other function to lock the file in a
> thread-safe manner.
>
> This is my function (that tries to lock the file):
>
> function TSpoolObjectReader.Open: boolean;
> begin
> {$I-} Rewrite(LockFile, 1); {$I+}
Rewrite does not cause an error if a file already exists. It simply
overwrites it. You cannot first check whether it exists and then
create it if it doesn't, because in between another thread could have
created the lock file already.
I think the easiest way to get cross-platform lockfile behaviour, is to
a) create the lockfile at the start of your program (e.g., a rewrite
followed by a close)
b) whenever you want to lock it, use
systutils.fileopen(lockfilename,fmOpenWrite or fmShareExclusive);
If that function returns -1, acquiring the lock failed.
Jonas
_______________________________________________
fpc-pascal maillist - fpc-pascal at lists.freepascal.org
http://lists.freepascal.org/mailman/listinfo/fpc-pascal
More information about the fpc-pascal
mailing list