summaryrefslogtreecommitdiff
path: root/rtl/unix/tthread.inc
blob: f6ee9b1dba040b943c0ddface9ab1b3555d892fb (plain)
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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
{
    This file is part of the Free Pascal run time library.
    Copyright (c) 1999-2000 by Peter Vreman
    Copyright (c) 2006 by Jonas Maebe
    members of the Free Pascal development team.

    Generic *nix TThread implementation

    See the file COPYING.FPC, included in this distribution,
    for details about the copyright.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

 **********************************************************************}



{
  What follows, is a short description on my implementation of TThread.
  Most information can also be found by reading the source and accompanying
  comments.

  A thread is created using BeginThread, which in turn calls
  pthread_create. So the threads here are always posix threads.
  Posix doesn't define anything for suspending threads as this is
  inherintly unsafe. Just don't suspend threads at points they cannot
  control. Therefore, I didn't implement .Suspend() if its called from
  outside the threads execution flow (except on Linux _without_ NPTL).

  The implementation for .suspend uses an RTLEvent, which is initialized
  at thread creation. If the thread tries to suspend itself, we simply
  let it wait on the Event until it is unblocked by someone else
  who calls .Resume.


  Johannes Berg <johannes@sipsolutions.de>, Sunday, November 16 2003
}

{ ok, so this is a hack, but it works nicely. Just never use
  a multiline argument with WRITE_DEBUG! }

{.$DEFINE DEBUG_MT}
{$MACRO ON}
{$IFDEF DEBUG_MT}
{$define WRITE_DEBUG := writeln} // actually write something
{$ELSE}
{$define WRITE_DEBUG := //}      // just comment out those lines
{$ENDIF}

var
  ThreadsInited: boolean = false;
const
  // stupid, considering its not even implemented...
  Priorities: array [TThreadPriority] of Integer =
   (-20,-19,-10,0,9,18,19);


procedure DoneThreads;
begin
  ThreadsInited := false;
end;

function ThreadFunc(parameter: Pointer): ptrint;
var
  LThread: TThread;
  LFreeOnTerminate: boolean;
{$ifdef DEBUG_MT}
  lErrorAddr, lErrorBase: Pointer;
{$endif}
begin
  WRITE_DEBUG('ThreadFunc is here...');
  LThread := TThread(parameter);
  WRITE_DEBUG('thread initing, parameter = ', ptruint(LThread));
  try
    // wait until AfterConstruction has been called, so we cannot
    // free ourselves before TThread.Create has finished
    // (since that one may check our VTM in case of $R+, and
    //  will call the AfterConstruction method in all cases)
//    LThread.Suspend;
    WRITE_DEBUG('AfterConstruction should have been called for ',ptruint(lthread));
    if LThread.FInitialSuspended then
      begin
        WRITE_DEBUG('thread ', ptruint(LThread), ' waiting for RTLEvent ', ptruint(LThread.FSuspendEvent));
        RtlEventWaitFor(LThread.FSuspendEvent);
        if not(LThread.FTerminated) then
          begin
            if not LThread.FSuspended then
              begin
                LThread.FInitialSuspended := false;
                CurrentThreadVar := LThread;
                WRITE_DEBUG('going into LThread.Execute');
                LThread.Execute;
              end
            else
              WRITE_DEBUG('thread ', ptruint(LThread), ' initially created suspended, resumed, but still suspended?!');
          end
        else
          WRITE_DEBUG('initially created suspended, but already terminated');
      end
     else
       begin
         LThread.FSuspendedInternal := true;
         WRITE_DEBUG('waiting for SuspendedInternal - ', LThread.ClassName);
         RtlEventWaitFor(LThread.FSuspendEvent);
         CurrentThreadVar := LThread;
         WRITE_DEBUG('going into LThread.Execute - ', LThread.ClassName);
         LThread.Execute;
       end;
  except
    on e: exception do begin
      LThread.FFatalException := TObject(AcquireExceptionObject);
{$ifdef DEBUG_MT}
      lErrorAddr:=ExceptAddr;
      lErrorBase:=ExceptFrames^;
      writeln(stderr,'Exception caught in thread $',hexstr(LThread),
        ' at $',hexstr(lErrorAddr));
      writeln(stderr,BackTraceStrFunc(lErrorAddr));
      dump_stack(stderr,lErrorBase);
      writeln(stderr);
{$endif}
      // not sure if we should really do this...
      // but .Destroy was called, so why not try FreeOnTerminate?
      if e is EThreadDestroyCalled then LThread.FFreeOnTerminate := true;
    end;
  end;
  WRITE_DEBUG('thread done running');
  Result := LThread.FReturnValue;
  WRITE_DEBUG('Result is ',Result);
  LFreeOnTerminate := LThread.FreeOnTerminate;
  LThread.DoTerminate;
  LThread.FFinished := True;
  if LFreeOnTerminate then
    begin
      WRITE_DEBUG('Thread ',ptruint(lthread),' should be freed');
      LThread.Free;
      WRITE_DEBUG('Thread freed');
      WRITE_DEBUG('thread func calling EndThread');
      // we can never come here if the thread has already been joined, because
      // this function is the thread's main function (so it would have terminated
      // already in case it was joined)
      EndThread(Result);
    end;
end;

{ TThread }
procedure TThread.SysCreate(CreateSuspended: Boolean;
                            const StackSize: SizeUInt);
begin
  FSuspendEvent := RtlEventCreate;
  WRITE_DEBUG('thread ', ptruint(self), ' created RTLEvent ', ptruint(FSuspendEvent));
  FSuspended := CreateSuspended;
  FThreadReaped := false;
  FInitialSuspended := CreateSuspended;
  FFatalException := nil;
  FSuspendedInternal := not CreateSuspended;
  WRITE_DEBUG('creating thread, self = ',ptruint(self));
  FHandle:= BeginThread(@ThreadFunc, Pointer(Self), FThreadID, StackSize);
  if FHandle = TThreadID(0) then
    raise EThread.create('Failed to create new thread');
  WRITE_DEBUG('TThread.Create done, fhandle = ', ptruint(fhandle));
end;


procedure TThread.SysDestroy;
begin
  if not assigned(FSuspendEvent) then
    { exception in constructor }
    exit;
  if (FHandle = TThreadID(0)) then
  { another exception in constructor }
    begin
      RtlEventDestroy(FSuspendEvent);
      exit;
    end;
  if (FThreadID = GetCurrentThreadID) then
    begin
      if not(FFreeOnTerminate) and not FFinished then
        raise EThreadDestroyCalled.Create('A thread cannot destroy itself except by setting FreeOnTerminate and leaving!');
      FFreeOnTerminate := false;
    end
  else
    begin
      // if someone calls .Free on a thread with not(FreeOnTerminate), there
      // is no problem. Otherwise, FreeOnTerminate must be set to false so
      // when ThreadFunc exits the main runloop, it does not try to Free
      // itself again
      FFreeOnTerminate := false;
      { you can't join yourself, so only for FThreadID<>GetCurrentThreadID }
      { and you can't join twice -> make sure we didn't join already       }
      if not FThreadReaped then
        begin
          Terminate;
          if (FSuspendedInternal or FInitialSuspended) then
            Resume;
          WaitFor;
        end;
    end;
  RtlEventDestroy(FSuspendEvent);
  FFatalException.Free;
  FFatalException := nil;
  { threadvars have been released by cthreads.ThreadMain -> DoneThread, or  }
  { or will be released (in case of FFreeOnTerminate) after this destructor }
  { has exited by ThreadFunc->EndThread->cthreads.CEndThread->DoneThread)   }
end;

procedure TThread.SetSuspended(Value: Boolean);
begin
  if Value <> FSuspended then
    if Value then
      Suspend
    else
      Resume;
end;

procedure TThread.Suspend;
begin
  if FThreadID = GetCurrentThreadID then
    begin
      if not FSuspended and
         (InterLockedExchange(longint(FSuspended),longint(longbool(true))) = longint(longbool(false))) then
        RtlEventWaitFor(FSuspendEvent)
    end
  else
    begin
      Raise EThread.create('Suspending one thread from inside another one is unsupported (because it is unsafe and deadlock prone) by *nix and posix operating systems');
    end;
end;


procedure TThread.Resume;
begin
  if FSuspendedInternal and (InterLockedExchange(longint(FSuspendedInternal),ord(false)) = longint(longbool(true))) then
    begin
      WRITE_DEBUG('resuming thread after TThread construction',ptruint(self));
      RtlEventSetEvent(FSuspendEvent);
    end
  else
    begin
      if FSuspended and
         { don't compare with ord(true) or ord(longbool(true)), }
         { becaue a longbool's "true" value is anyting <> false }
         (InterLockedExchange(longint(FSuspended),longint(false)) <> longint(longbool(false))) then
        begin
          WRITE_DEBUG('resuming ',ptruint(self));
          RtlEventSetEvent(FSuspendEvent);
        end
    end
end;


function TThread.WaitFor: Integer;
begin
  WRITE_DEBUG('waiting for thread ',ptruint(FHandle));
  If (MainThreadID=GetCurrentThreadID) then 
    {
     FFinished is set after DoTerminate, which does a synchronize of OnTerminate, 
     so make sure synchronize works (or indeed any other synchronize that may be 
     in progress)
    }
    While not FFinished do  
      CheckSynchronize(100);
  WaitFor := WaitForThreadTerminate(FHandle, 0);
  { should actually check for errors in WaitForThreadTerminate, but no }
  { error api is defined for that function                             }
  FThreadReaped:=true;
  WRITE_DEBUG('thread terminated');
end;

procedure TThread.CallOnTerminate;
begin
  // no need to check if FOnTerminate <> nil, because
  // thats already done in DoTerminate
  FOnTerminate(self);
end;

procedure TThread.DoTerminate;
begin
  if Assigned(FOnTerminate) then
    Synchronize(@CallOnTerminate);
end;

function TThread.GetPriority: TThreadPriority;
var
  P: Integer;
  I: TThreadPriority;
begin
  P := ThreadGetPriority(FHandle);
  Result := tpNormal;
  for I := Low(TThreadPriority) to High(TThreadPriority) do
    if Priorities[I] = P then
      Result := I;
end;


procedure TThread.SetPriority(Value: TThreadPriority);
begin
  ThreadSetPriority(FHandle, Priorities[Value]);
end;