Pthread Lock Wait
1. Background
In distributed training scenarios for large PyTorch models, the DataLoader and pin_memory modules use a multithreaded producer-consumer model and rely on pthread mutexes (pthread_mutex_t) to protect concurrent access to shared queues.
The training runs on a multi-NPU server, with a data loading thread pool configured with 16 worker threads. The main thread retrieves data from the queue and feeds it to the NPU for computation. As the batch size increases and data preprocessing becomes more complex, training performance degrades.
2. Source
Training
3. Symptoms
The issue can be consistently reproduced.
Computation bottleneck:
- NPU utilization decreases, and device idle time increases while the NPU waits for computation tasks to be dispatched from the host.
- The time per training step increases, resulting in lower overall training throughput.
System-level symptoms:
- Overall CPU utilization is not high, but clear lock wait characteristics are observed.
pidstat -wshows a high thread context switch frequency.
Application-level symptoms:
- Logs show that actual data preprocessing accounts for only 40% of thread execution time, with the remaining time spent waiting.
- Increasing the number of worker threads to 32 does not improve performance and instead causes further degradation.
For details, see the following figure.

4. Troubleshooting Process
Use the perf tool for process-level performance sampling.
- Run
perf record -g -p <pid> sleep 30to collect performance hotspots of the training process. - The performance flame graph shows that
pthread_mutex_lockaccounts for a high proportion. - Lock contention mainly occurs during push and pop operations on the data queue.
- Run
Use the strace tool to perform system call tracking.
- Run
strace -tt -T -e futex -p <pid>to trackfutexsystem calls. - A large number of
futex(FUTEX_WAIT)calls are observed, with individual wait durations exceeding 10 ms.
- Run
Use MSOSRT to collect the execution time of system library functions.
OSRT stands for OS Runtime Libraries Trace. Its core capability is to collect and trace calls to various user-space library function APIs based on Linux system runtime libraries.
MindStudio OSRT (MSOSRT) is an OSRT tool provided by MindStudio. It focuses on performance analysis by specifically collecting typical APIs with long execution time in the Linux C standard library and POSIX thread (
pthread) library, particularly functions such asread,ioctl, andpthread_mutex_lockthat may cause user processes to enter a blocking wait state. By collecting the execution time and distribution of these function calls, MSOSRT helps developers quickly locate and analyze the root causes of process blocking.Repository: MSOSRT
Usage:
Build the MSOSRT tool.
Download the source code repository to the local environment and run
bashbuild.shto generate thelibmsosrt_trace.solibrary.Run
export LD_PRELOAD=./libmsosrt_trace.so:$LD_PRELOADto addlibmsosrt_trace.soto theLD_PRELOADenvironment variable.Set the environment variables for the detection threshold and export mode (real-time printing or file export; avoid enabling both modes simultaneously):
# Detection threshold. A positive integer. Only library functions whose duration exceeds the threshold are recorded. Unit: ns. Default: 10000000. export MSOSRT_TRACE_THRESHOLD=10000000 # Real-time printing. A positive integer. Set to 1 to print detection results in real time without writing them to a file. Default: 0. export MSOSRT_REALTIME_PRINT=1 # File export. A string specifying the directory for exporting detection results. Default: current directory. export MSOSRT_EXPORT_PATH="./osrt_trace_result"Run the training process.
If real-time printing is selected, detection results are printed in real time while the user process is running, as shown in the following figure:
Pid: 2328177, Tid: 2328280, Function: pthread_cond_wait, StartTime: 1725398310787080000, Duration: 3088062410 Pid: 2328177, Tid: 2328282, Function: pthread_cond_wait, StartTime: 1725398310787170000, Duration: 3087994240 Pid: 2328177, Tid: 2328480, Function: read, StartTime: 1725398318916180000, Duration: 100509970 Pid: 2328177, Tid: 2328440, Function: ioctl, StartTime: 1725398319218640000, Duration: 512040720 Pid: 2328177, Tid: 2328177, Function: free, StartTime: 1725398330504550000, Duration: 56386880If file export is selected, detection results are generated in the directory specified by
MSOSRT_EXPORT_PATHafter the user process exits. The result file is namedmsosrt_trace_{process_id}_{process_name}.csv, such asmsosrt_trace_2328177_python3.csv. The file contains information such as the process ID (PID), thread ID (TID), function name, start time, and duration, as shown in the following table.Pid Tid Function StartTime(ns) Duration(ns) 2328177 2328280 pthread_cond_wait 1725398310787080000 3088062410 2328177 2328282 pthread_cond_wait 1725398310787170000 3087994240 2328177 2328480 read 1725398318916180000 100509970 2328177 2328440 ioctl 1725398319218640000 512040720 2328177 2328177 free 1725398330504550000 56386880 From the detection results, it can be observed that the
pthread_cond_waitfunction accounts for a relatively high proportion, which is the main cause of lock waiting. At the same time, functions such as read and ioctl also account for a relatively high proportion, which is the main cause of the time consumed by the data preprocessing logic. Based on this information, we can locate the performance bottleneck in the data preprocessing logic.
5. Root Cause
Incorrect lock granularity:
- The entire data preprocessing process (decoding, augmentation, and normalization) is executed within the critical section instead of acquiring the lock only for queue operations.
- The lock is held for too long (8 ms on average), preventing other worker threads from enqueueing data and effectively serializing execution.
Improper lock type configuration:
- The default
PTHREAD_MUTEX_TIMED_NPtype is used, resulting in significant performance degradation under high contention. PTHREAD_MUTEX_ADAPTIVE_NPadaptive locking is not enabled, resulting in excessive futex waits in kernel space.
- The default
6. Troubleshooting Methodology Summary
For thread lock wait scenarios, prioritize the following troubleshooting steps:
First, use the lock analysis capabilities of perf.
- Run
perf recordto quickly determine whether lock contention exists and identify the lock objects experiencing the most severe contention. - Generate a flame graph and examine the CPU proportions of
pthread_mutex_lockandpthread_cond_wait. A high proportion may indicate a thread lock issue.
- Run
Use the MSOSRT tool for detailed analysis.
- Use the MSOSRT detection results to identify
pthread_cond_waitas the primary cause of lock waits. - Analyze functions such as
readandioctl, which account for high proportions and are the primary contributors to the time spent on data preprocessing.
- Use the MSOSRT detection results to identify
7. Suggestions for Tool Improvement
Enhance msProf by integrating perf:
- Integrate perf into msProf so that lock detection can directly output statistics on lock hold time, rather than only wait time.
- Add call stack tracing for lock contention to directly show which function path holds the lock for the longest time.
Add a lock contention visualization tool.
- Provide real-time monitoring of the lock wait queue length.
- Provide a dependency graph showing relationships between lock holders and waiters.