Fix excessive thread name lookups #790
                
     Open
            
            
          
  Add this suggestion to a batch that can be applied as a single commit.
  This suggestion is invalid because no changes were made to the code.
  Suggestions cannot be applied while the pull request is closed.
  Suggestions cannot be applied while viewing a subset of changes.
  Only one suggestion per line can be applied in a batch.
  Add this suggestion to a batch that can be applied as a single commit.
  Applying suggestions on deleted lines is not supported.
  You must change the existing code in this line in order to create a valid suggestion.
  Outdated suggestions cannot be applied.
  This suggestion has been applied or marked resolved.
  Suggestions cannot be applied from pending reviews.
  Suggestions cannot be applied on multi-line comments.
  Suggestions cannot be applied while the pull request is queued to merge.
  Suggestion cannot be applied right now. Please check back later.
  
    
  
    
py-spy uses a cache to minimize the overhead of looking up Python thread names during sampling. If looking up a thread name fails, the entire cache is rebuilt. However, if a failure is persistent, this causes the cache to be rebuilt during every sample (potentially more than once), creating excessive overhead.
Two cases when persistent thread name lookup failures can occur are:
threadingmodule has not been importedthreadingmodule, such as through_thread.start_new_threadFix this by modifying the cache to store a negative response (
None) if the thread name is still not found after rebuilding the cache. To prevent negative responses from being lost when more than one thread name lookup fails, add a flag preventing the cache from being rebuilt more than once per sample.One disadvantage of this approach is that in nonblocking mode, a spurious negative response can be cached for an extended duration. This happens if the thread is created during a sample and after the single allowed thread name lookup happens.