i added uses cthreads to the program or else the function wouldn't even wait 2.5 seconds
but the funtion seems to still block the writeln('waited 2.5 secs'); line
if the nosleep wasn't blocking it would print out '11' after the '22' and not before
program timer;
uses cthreads;
function nosleep(timeout: integer): PRTLEvent;
begin
result := RTLEventCreate;
RTLEventWaitFor(result, timeout);
RTLEventDestroy(result);
writeln('11');
end;
begin
nosleep(2500);
writeln('22');
end.
Again, what do you expect your sleep alternative to do? Computers are stupid, they just execute one instruction after another. So any function like sleep, would need to be able to tell the computer what to do during that time.
How does the computer know what functions require the waiting and what don't? Assume there is a non blocking wait function called nbwait, what should happen in the following example:
procedure Test;
begin
nbwait(1000);
WriteLn('a');
WriteLn('b');
end;
begin
Test;
WriteLn('c');
end.
Here are 3 equally valid options:
1. nbWait does literally nothing and a, b and c are printed right after each other in order
2. nbwait delays the next statement, so the writing of a, so b and c are written immediately and a is waited for
3. nbwait delays the current function and c is written but a and b are waited for
The first would probably be useless. The second is not possible in pascal, this would require some callback. The third option would require nbwait to know the context of the function and also if that function produces a result, the calling function can't know when it's finished.
Such an nbwait function simply cannot exist. Either you use threads, or you use something like async await.
If you want to do async-await style programming, you could try out the aforementioned STAX. Your example would be:
program Project1;
{$mode objfpc}{$H+}
uses
SysUtils,stax,stax.functional;
procedure NoSleep(AExecutor: TExecutor);
begin
AsyncSleep(2500);
WriteLn('11');
end;
procedure Test(AExecutor: TExecutor);
begin
RunAsync(AsyncProcedure(@NoSleep));
WriteLn('22');
end;
var
exec: TExecutor;
begin
exec := TExecutor.Create;
exec.RunAsync(AsyncProcedure(@Test));
exec.Run;
exec.Free;
ReadLn;
end.
But, it's kindof a hack. Instead you should probably reconsider either using threads, or using a different language that has async-await supported on the language level