title: Lock.protect and callsame
body: <p>I'm trying to write a trait to threadsafe a <code>sub</code> automagically.  This is what I've got:</p>
  <pre><code>#| A trait to ensure that a sub is not run on multiple threads simultaneously.
  multi sub trait_mod:&lt;is&gt; (Sub \code, :$protected!) {
  
      # If :!protected, do nothing.
      if $protected {
  
          # Create a new lock outside the multithreaded area
          my $lock = Lock.new;
  
          # Wrap the sub with a routine that hides callsame in a lock
          code.wrap: sub (|) {
              $lock.protect: {callsame}
          }
      }
  }
  
  #| Should print &quot;Start X and finish X&quot; if properly protected
  sub needs-protection($x) is protected {
     print &quot;Start $x and &quot;;
     sleep 1;
     say &quot;finish $x&quot;;
  }
  
  # Test it out.
  # If not protected, completes in 1 second with malformed output
  (1..4).hyper(:1batch, :4degree) { 
     needs-protection $_
  }
  </code></pre>
  <p>However, AFAICT, it seems that the <code>callsame</code> isn't doing anything (it returns <code>Nil</code> but that's it).  My guess is that it's somehow attempting to call a different candidate for <code>.protect</code>, but I don't see a way to ensure that the <code>callsame</code> is linked to the wrapped sub, rather than some other method.</p>
  <p>I was able to get it to work by doing</p>
  <pre><code>multi sub trait_mod:&lt;is&gt; (Sub \code, :$protected!) {
      if $protected {
          my $lock = Lock.new;
          code.wrap: sub (|c) {
              if CALLERS::&lt;$*PROTECTED&gt; {
                  $*PROTECTED = False;
                  return callsame;
              }
  
              $lock.protect: { 
                  my $*PROTECTED = True;
                  code.CALL-ME(|c);
              }
          }
      }
  }
  </code></pre>
  <p>But that feels cludgy and I'm probably missing something that allows a <code>True</code> value for <code>$*PROTECTED</code> to slip out when things aren't safe.  Is there a way to make a direct <code>callsame</code> while inside of a <code>protect</code>-ed block?</p>