12.6.8 Thread-local Variables

Thread-local variables are defined within the scope of execution of a thread on the system. To indicate that a variable is thread-local, you prefix it with self-> as shown in the following example.

#pragma D option quiet

  self->t = timestamp; /* Initialize a thread-local variable */

/self->t != 0/
  printf("%s (pid:tid=%d:%d) spent %d microseconds in read()\n",
  execname, pid, tid, ((timestamp - self->t)/1000)); /* Divide by 1000 -> microseconds */

  self->t = 0; /* Reset the variable */

This D program (dtrace.d) displays the command name, process ID, thread ID, and expired time in microseconds whenever a process invokes the read() system call.

# dtrace -s readtrace.d
nome-terminal (pid:tid=2774:2774) spent 27 microseconds in read()
gnome-terminal (pid:tid=2774:2774) spent 16 microseconds in read()
hald-addon-inpu (pid:tid=1662:1662) spent 26 microseconds in read()
hald-addon-inpu (pid:tid=1662:1662) spent 17 microseconds in read()
Xorg (pid:tid=2046:2046) spent 18 microseconds in read()