tryLockWithTimeout attempts to acquire the lock within the specified timeout period.
(lock *sync.Mutex, startTime time.Time, maxWait time.Duration)
| 408 | |
| 409 | // tryLockWithTimeout attempts to acquire the lock within the specified timeout period. |
| 410 | func tryLockWithTimeout(lock *sync.Mutex, startTime time.Time, maxWait time.Duration) bool { |
| 411 | // Calculate remaining wait time based on transaction start time. |
| 412 | remainingTime := maxWait - time.Since(startTime) |
| 413 | if remainingTime <= 0 { |
| 414 | return false |
| 415 | } |
| 416 | |
| 417 | // Create a context with timeout for lock acquisition. |
| 418 | ctx, cancel := context.WithTimeout(context.Background(), remainingTime) |
| 419 | defer cancel() |
| 420 | |
| 421 | // Use channel for timeout control. |
| 422 | done := make(chan bool, 1) |
| 423 | go func() { |
| 424 | lock.Lock() |
| 425 | done <- true |
| 426 | }() |
| 427 | |
| 428 | // Wait for either lock acquisition or timeout. |
| 429 | select { |
| 430 | case <-done: |
| 431 | return true |
| 432 | case <-ctx.Done(): |
| 433 | return false |
| 434 | } |
| 435 | } |