crittest.pp 851 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. program crittest;
  2. // originally a test to test .tryenter.
  3. // A thread holds a lock for 5sec, while the main thread tries to lock
  4. // it.
  5. {$mode Delphi}
  6. Uses {$ifdef unix}cthreads,{$endif} syncobjs,sysutils,classes;
  7. type TTestthread = class(tthread)
  8. procedure execute; override;
  9. end;
  10. var crit : TCriticalSection;
  11. procedure TTestThread.Execute;
  12. begin
  13. crit.acquire;
  14. sleep(5000);
  15. crit.release;
  16. end;
  17. var thr : TTestthread;
  18. I : integer;
  19. begin
  20. crit:=TCriticalsection.create;
  21. thr :=TTestthread.Create(false);
  22. sleep(500); // give thread time to start.
  23. writeln('tryenter');
  24. i:=0;
  25. while not(crit.tryenter) do
  26. begin
  27. writeln('tryenter attempt ',i);
  28. inc(i);
  29. sleep(100);
  30. end;
  31. writeln('lock acquired in mainthread!');
  32. writeln('no payload, so releasing');
  33. crit.release;
  34. thr.waitfor;
  35. end.