1

Is there a way to make threads executing a C program to sleep at arbitrary points of execution?

I'm interested of testing the robustness of an implementation of distributed algorithm and I'd like to run different scenarios repeatedly so that threads would be suspended randomly.

(Adding sleeps to the code is not what I'm looking for.)

Thanks!

vraa
  • 349
  • 2
  • 8
  • 2
    Send it a signal and `sleep` in the signal handler. That will give you arbitrary *times* when sleep occurs but not sure whether that's what you mean or you need to control the exact line of code where it sleeps. – kaylum Nov 07 '21 at 19:44
  • Maybe try writing a gdb script to have it pause execution at random times, for random amounts of time, and then continue. – 404 Not Found Nov 07 '21 at 19:46
  • The idea is to have unpredictable sleeps. I found actually a promising answer here, https://stackoverflow.com/questions/9397068/how-to-pause-a-pthread-any-time-i-want and it's based on user-defined signals. – vraa Nov 07 '21 at 19:54
  • Have you thought of randomly locking a mutex (or semaphore, depending on the case)? – Leonardo Araujo Nov 08 '21 at 02:06
  • @Leonardo Araujo yes, that's what I currently have but its limited to mutexing only. I want random slowness, and record added sleeps for each test run so that it can be repeated in case of test failure. – vraa Nov 08 '21 at 19:35
  • Program your software in a continuation passing style, with event loops. See [RefPerSys](http://refpersys.org/) and its agenda – Basile Starynkevitch Nov 08 '21 at 19:39
  • [`kill()`](https://pubs.opengroup.org/onlinepubs/9699919799/functions/kill.html) and [`signal()`](https://pubs.opengroup.org/onlinepubs/9699919799/functions/signal.html) perhaps? – pmg Nov 13 '21 at 18:55

1 Answers1

1

I'd like to run different scenarios repeatedly so that threads would be suspended randomly.

One way to achieve this (on a UNIX system) is to run the program under a debugger, which can suspend and resume threads at arbitrary points in time.

Debugger here doesn't mean GDB -- it could be any program utilizing ptrace to control the target.

Unfortunately writing such a control program / debugger from scratch is quite involved -- you'll need to implement a lot of low-level thread tracking.

Since you control the target program, you can cheat by making it create all the threads, then block them all before doing any work. Now the debugger program can attach all the threads, unblock them, and start suspending them at random.

Another alternative is to modify an existing debugger to do your bidding. This would be hard to do with GDB, but is probably easier with LLDB.

Employed Russian
  • 199,314
  • 34
  • 295
  • 362