Dust and Stars - 1992 | Chapter 146 | Lock and Leeway | English
Exactly nine o'clock. The terminal cursor blinked rhythmically in the blank space. Lin Chen didn't immediately type out the full c
Chapter 146: Lock and Leeway
Exactly nine o'clock. The terminal cursor blinked rhythmically in the blank space.
Lin Chen didn't immediately type out the full code. He first locked down the structure with three lines of comments: initialize capacity, doubly linked list nodes, hash map. Python 2.7's collections.OrderedDict already implemented a doubly linked list under the hood, but during concurrent reads and writes, dictionary resizing and linked list reordering would trigger race conditions. He had to implement manual locking.
The first version's logic was straightforward: wrap the entire get and put methods with a threading.Lock(). After writing it, he ran a local simulated stress test with ten threads. The terminal froze, CPU usage instantly spiked to 90%, and response times broke past 40ms. The coarse-grained lock serialized the concurrency; the memory limit hadn't been breached, but performance died first.
He deleted those five lines of code. His fingers hovered over the keyboard for two seconds. The numbness at his left ankle was creeping up his calf muscles, like a thin thread soaked in ice water. He adjusted his posture, planting his right foot firmly on the floor while resting his left heel lightly. The ibuprofen was slowly releasing in his stomach, bringing a heavy, dull clarity.
For the second version, he switched to fine-grained control. Read operations would only acquire a read lock, while write operations would take a write lock. The Python standard library lacked a native read-write lock, so he simulated one using a threading.Condition paired with a state counter. When a read thread entered, it checked the write lock status; if no write was in progress, it was allowed through. When a write thread entered, it blocked all reads. After finishing the logic, he manually inserted a memory counter: each time a new key was put, current_size incremented by one; when it exceeded the 50MB threshold, it would force a popitem(last=False) to evict the oldest node, and explicitly del to release the reference.
9:42. Local tests passed. Average response time: 7.2ms, peak memory: 43MB.
He let out a long breath, the T-shirt on his back already sticking to the chair. The air conditioning in the server room was set high, cold air blowing straight down from the vent, raising a fine layer of goosebumps. Next to him, a guy in a polo shirt was frowning at his MacBook, the screen displaying a Java ConcurrentHashMap implementation with three times his lines of code. Lin Chen didn't look; he just stared at his own terminal. He created a new stress test script to simulate edge cases under high concurrency: key collisions, capacity maxed out, frequent evictions.
9:51. The test crashed.
The terminal threw a RuntimeError: dictionary changed size during iteration. While he was iterating to clean up old nodes, another write thread had modified the dictionary simultaneously. The iterator had been invalidated. He closed his eyes, running through the execution stack in his head. The problem was that the cleanup logic wasn't fully wrapped inside the write lock. He opened his eyes, moved the popitem and del operations entirely into the write lock's critical section, and added a try-finally block around the outer loop to guarantee lock release.
9:56. Repackaged. Compressed into lru_cache_v2.tar.gz. Uploaded to the intranet review server. The progress bar crawled upward: 10%… 45%… 88%… 100%.
[SUCCESS] Submission received.
He released the mouse. His knuckles were pale from prolonged tension, trembling slightly. He leaned back in his chair and closed his eyes. The server room was left with only the low hum of cooling fans and the occasional clack of keyboards. The cicadas' cries outside were filtered through double-paned glass, reduced to a distant background hum.
10:05. Footsteps stopped beside his desk.
Zhou Yan pulled over a chair and sat down. Without a word, he opened Lin Chen's code. The mouse wheel scrolled rapidly, stopping at the read-write lock simulation section. Zhou Yan pushed up his black-rimmed glasses. "Using a Condition to simulate read-write separation, the approach is sound. But notifyAll in high-frequency read scenarios will wake up all waiting threads. The overhead from context switching will eat up the two milliseconds you saved."
Lin Chen opened his eyes. "I know. The test set's concurrency is under fifty, so the thundering herd overhead stays within the threshold. If this went to production, I'd rewrite the core layer with a C extension, or switch to the Gevent coroutine model. But the training camp machines run Python 2.7. The standard library is the most stable choice."
Zhou Yan looked at him for two seconds. His gaze moved from the worn edges of his old laptop to the neat comments on the screen. "Pragmatic. Run the official stress test."
He hit Enter. The intranet test script launched. The progress bar rolled. The final result popped up: Avg Latency: 6.8ms | Peak Mem: 41.2MB | Pass Rate: 100%.
Zhou Yan ticked a box on the grading sheet. "Skip auditing the basic classes this afternoon. Go to the server room on the third floor of Building B and find Engineer Li. He's got a log parsing project from half a year ago. Regular expressions can't handle it, memory keeps crashing, and the client is breathing down his neck. Take it over."
Lin Chen nodded. "Alright."
Zhou Yan stood up, took two steps, then stopped. "Second drawer on the left in the server room has soda crackers and stomach medicine. Ibuprofen on an empty stomach damages the gastric mucosa. Help yourself."
Lin Chen didn't speak, just nodded again. Zhou Yan turned and left, his footsteps fading into the distance.
He pulled open the drawer. Half a pack of crushed soda crackers, a bottle of hydrotalcite. He tore open the wrapper and took a bite. It was dry, crumbs falling into the keyboard crevices. He picked up his water glass and took a large gulp, the cold water sliding down his esophagus, suppressing the churning acidity in his stomach.
His phone vibrated in his canvas bag. He pulled it out. The screen lit up with a text message from his hometown. Only one signal bar, the text fragmented: "Xiao Man didn't have a seizure today. The town clinic says the sodium valproate is almost out. Is everything going smoothly on your end? Don't overwork yourself."
Sender: Wang Guiying.
The cold air from the server room's AC kept blowing. He stared at the line of text, his thumb hovering over the keyboard. Outside, the sunlight shifted, the stripes of the blinds cutting across the desk, landing precisely on the back of his left hand. He typed his reply: "Going smoothly. Will wire the medicine money tomorrow. Take it on schedule. Don't skimp."
He pressed send. The progress bar spun twice, showing delivered.
He shoved the phone back into his pocket. His left foot twitched again, the muscle tensing uncontrollably. He reached down and rubbed his calf, pressing hard until the pain overpowered the numbness. Then, he placed his hands back on the keyboard. Opened a new terminal. cd /project/logs.
The afternoon's log parsing would be dealing with truly dirty data. No standardized fields, no unified encoding, just hundreds of thousands of lines of raw text mixed with timestamps, garbled characters, and truncated strings. He had to figure out the structure and write a parser before dinner.
The cursor blinked. Waiting for input.
More from WayDigital
Continue through other published articles from the same publisher.
Comments
0 public responses
All visitors can read comments. Sign in to join the discussion.
Log in to comment