I'm trying to write a DTrace script which does the following:
- Whenever a new thread is started, increment a count.
- Whenever one of these threads exits, decrement the count, and exit the script if the count is now zero.
I have something like this:
BEGIN {
threads_alive = 0;
}
proc:::lwp-start /execname == $$1/ {
self->started = timestamp;
threads_alive += 1;
}
proc:::lwp-exit /self->started/ {
threads_alive -= 1;
if (threads_alive == 0) {
exit(0);
}
}
However, this doesn't work, because threads_alive
is a scalar variable and thus it is not multi-cpu safe. As a result, multiple threads will overwrite each other's changes to the variable.
I have also tried using an aggregate variable instead:
@thread_count = sum(1)
//or
@threads_entered = count();
@threads_exitted = count();
Unfortunately, I haven't found syntax to be able to do something like @thread_count == 0
or @threads_started == @threads_stopped
.