-
Notifications
You must be signed in to change notification settings - Fork 0
/
mutex.pas
53 lines (40 loc) · 924 Bytes
/
mutex.pas
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
unit mutex;
interface
uses Windows, SysUtils;
function GetExclusivity(const Name: string): boolean;
procedure ReleaseExclusivity(const Name: string);
implementation
uses Classes;
var
HeldHandles: TStringList;
function GetExclusivity(const Name: string): boolean;
var
res: HResult;
begin
res := CreateMutex(nil,true,pchar(Name));
if (res = 0) or (GetLastError = ERROR_ALREADY_EXISTS) then
begin
result := false;
exit;
end
else
begin
HeldHandles.AddObject(Name,TObject(res));
result := true;
end;
end;
procedure ReleaseExclusivity(const Name: string);
var
idx: integer;
begin
idx := HeldHandles.IndexOf(Name);
if idx = -1 then
raise exception.create('We do not hold this handle');
CloseHandle(integer(HeldHandles.Objects[idx]));
HeldHandles.Delete(idx);
end;
initialization
HeldHandles := TStringList.Create;
finalization
HeldHandles.Free;
end.