]> git.lizzy.rs Git - rust.git/blob - src/libstd/io/stdio.rs
doc: Stdin is locked for reads, not writes
[rust.git] / src / libstd / io / stdio.rs
1 // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 use prelude::v1::*;
12 use io::prelude::*;
13
14 use cell::{RefCell, BorrowState};
15 use fmt;
16 use io::lazy::Lazy;
17 use io::{self, BufReader, LineWriter};
18 use sync::{Arc, Mutex, MutexGuard};
19 use sys::stdio;
20 use sys_common::remutex::{ReentrantMutex, ReentrantMutexGuard};
21 use thread::LocalKeyState;
22
23 /// Stdout used by print! and println! macros
24 thread_local! {
25     static LOCAL_STDOUT: RefCell<Option<Box<Write + Send>>> = {
26         RefCell::new(None)
27     }
28 }
29
30 /// A handle to a raw instance of the standard input stream of this process.
31 ///
32 /// This handle is not synchronized or buffered in any fashion. Constructed via
33 /// the `std::io::stdio::stdin_raw` function.
34 struct StdinRaw(stdio::Stdin);
35
36 /// A handle to a raw instance of the standard output stream of this process.
37 ///
38 /// This handle is not synchronized or buffered in any fashion. Constructed via
39 /// the `std::io::stdio::stdout_raw` function.
40 struct StdoutRaw(stdio::Stdout);
41
42 /// A handle to a raw instance of the standard output stream of this process.
43 ///
44 /// This handle is not synchronized or buffered in any fashion. Constructed via
45 /// the `std::io::stdio::stderr_raw` function.
46 struct StderrRaw(stdio::Stderr);
47
48 /// Constructs a new raw handle to the standard input of this process.
49 ///
50 /// The returned handle does not interact with any other handles created nor
51 /// handles returned by `std::io::stdin`. Data buffered by the `std::io::stdin`
52 /// handles is **not** available to raw handles returned from this function.
53 ///
54 /// The returned handle has no external synchronization or buffering.
55 fn stdin_raw() -> io::Result<StdinRaw> { stdio::Stdin::new().map(StdinRaw) }
56
57 /// Constructs a new raw handle to the standard output stream of this process.
58 ///
59 /// The returned handle does not interact with any other handles created nor
60 /// handles returned by `std::io::stdout`. Note that data is buffered by the
61 /// `std::io::stdout` handles so writes which happen via this raw handle may
62 /// appear before previous writes.
63 ///
64 /// The returned handle has no external synchronization or buffering layered on
65 /// top.
66 fn stdout_raw() -> io::Result<StdoutRaw> { stdio::Stdout::new().map(StdoutRaw) }
67
68 /// Constructs a new raw handle to the standard error stream of this process.
69 ///
70 /// The returned handle does not interact with any other handles created nor
71 /// handles returned by `std::io::stderr`.
72 ///
73 /// The returned handle has no external synchronization or buffering layered on
74 /// top.
75 fn stderr_raw() -> io::Result<StderrRaw> { stdio::Stderr::new().map(StderrRaw) }
76
77 impl Read for StdinRaw {
78     fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { self.0.read(buf) }
79     fn read_to_end(&mut self, buf: &mut Vec<u8>) -> io::Result<usize> {
80         self.0.read_to_end(buf)
81     }
82 }
83 impl Write for StdoutRaw {
84     fn write(&mut self, buf: &[u8]) -> io::Result<usize> { self.0.write(buf) }
85     fn flush(&mut self) -> io::Result<()> { Ok(()) }
86 }
87 impl Write for StderrRaw {
88     fn write(&mut self, buf: &[u8]) -> io::Result<usize> { self.0.write(buf) }
89     fn flush(&mut self) -> io::Result<()> { Ok(()) }
90 }
91
92 enum Maybe<T> {
93     Real(T),
94     Fake,
95 }
96
97 impl<W: io::Write> io::Write for Maybe<W> {
98     fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
99         match *self {
100             Maybe::Real(ref mut w) => handle_ebadf(w.write(buf), buf.len()),
101             Maybe::Fake => Ok(buf.len())
102         }
103     }
104
105     fn flush(&mut self) -> io::Result<()> {
106         match *self {
107             Maybe::Real(ref mut w) => handle_ebadf(w.flush(), ()),
108             Maybe::Fake => Ok(())
109         }
110     }
111 }
112
113 impl<R: io::Read> io::Read for Maybe<R> {
114     fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
115         match *self {
116             Maybe::Real(ref mut r) => handle_ebadf(r.read(buf), 0),
117             Maybe::Fake => Ok(0)
118         }
119     }
120     fn read_to_end(&mut self, buf: &mut Vec<u8>) -> io::Result<usize> {
121         match *self {
122             Maybe::Real(ref mut r) => handle_ebadf(r.read_to_end(buf), 0),
123             Maybe::Fake => Ok(0)
124         }
125     }
126 }
127
128 fn handle_ebadf<T>(r: io::Result<T>, default: T) -> io::Result<T> {
129     #[cfg(windows)]
130     const ERR: i32 = ::sys::c::ERROR_INVALID_HANDLE as i32;
131     #[cfg(not(windows))]
132     const ERR: i32 = ::libc::EBADF as i32;
133
134     match r {
135         Err(ref e) if e.raw_os_error() == Some(ERR) => Ok(default),
136         r => r
137     }
138 }
139
140 /// A handle to the standard input stream of a process.
141 ///
142 /// Each handle is a shared reference to a global buffer of input data to this
143 /// process. A handle can be `lock`'d to gain full access to [`BufRead`] methods
144 /// (e.g. `.lines()`). Reads to this handle are otherwise locked with respect
145 /// to other reads.
146 ///
147 /// This handle implements the `Read` trait, but beware that concurrent reads
148 /// of `Stdin` must be executed with care.
149 ///
150 /// Created by the [`io::stdin`] method.
151 ///
152 /// [`io::stdin`]: fn.stdin.html
153 /// [`BufRead`]: trait.BufRead.html
154 #[stable(feature = "rust1", since = "1.0.0")]
155 pub struct Stdin {
156     inner: Arc<Mutex<BufReader<Maybe<StdinRaw>>>>,
157 }
158
159 /// A locked reference to the `Stdin` handle.
160 ///
161 /// This handle implements both the [`Read`] and [`BufRead`] traits, and
162 /// is constructed via the [`Stdin::lock`] method.
163 ///
164 /// [`Read`]: trait.Read.html
165 /// [`BufRead`]: trait.BufRead.html
166 /// [`Stdin::lock`]: struct.Stdin.html#method.lock
167 #[stable(feature = "rust1", since = "1.0.0")]
168 pub struct StdinLock<'a> {
169     inner: MutexGuard<'a, BufReader<Maybe<StdinRaw>>>,
170 }
171
172 /// Constructs a new handle to the standard input of the current process.
173 ///
174 /// Each handle returned is a reference to a shared global buffer whose access
175 /// is synchronized via a mutex. If you need more explicit control over
176 /// locking, see the [`lock() method`][lock].
177 ///
178 /// [lock]: struct.Stdin.html#method.lock
179 ///
180 /// # Examples
181 ///
182 /// Using implicit synchronization:
183 ///
184 /// ```
185 /// use std::io::{self, Read};
186 ///
187 /// # fn foo() -> io::Result<String> {
188 /// let mut buffer = String::new();
189 /// try!(io::stdin().read_to_string(&mut buffer));
190 /// # Ok(buffer)
191 /// # }
192 /// ```
193 ///
194 /// Using explicit synchronization:
195 ///
196 /// ```
197 /// use std::io::{self, Read};
198 ///
199 /// # fn foo() -> io::Result<String> {
200 /// let mut buffer = String::new();
201 /// let stdin = io::stdin();
202 /// let mut handle = stdin.lock();
203 ///
204 /// try!(handle.read_to_string(&mut buffer));
205 /// # Ok(buffer)
206 /// # }
207 /// ```
208 #[stable(feature = "rust1", since = "1.0.0")]
209 pub fn stdin() -> Stdin {
210     static INSTANCE: Lazy<Mutex<BufReader<Maybe<StdinRaw>>>> = Lazy::new(stdin_init);
211     return Stdin {
212         inner: INSTANCE.get().expect("cannot access stdin during shutdown"),
213     };
214
215     fn stdin_init() -> Arc<Mutex<BufReader<Maybe<StdinRaw>>>> {
216         let stdin = match stdin_raw() {
217             Ok(stdin) => Maybe::Real(stdin),
218             _ => Maybe::Fake
219         };
220
221         // The default buffer capacity is 64k, but apparently windows
222         // doesn't like 64k reads on stdin. See #13304 for details, but the
223         // idea is that on windows we use a slightly smaller buffer that's
224         // been seen to be acceptable.
225         Arc::new(Mutex::new(if cfg!(windows) {
226             BufReader::with_capacity(8 * 1024, stdin)
227         } else {
228             BufReader::new(stdin)
229         }))
230     }
231 }
232
233 impl Stdin {
234     /// Locks this handle to the standard input stream, returning a readable
235     /// guard.
236     ///
237     /// The lock is released when the returned lock goes out of scope. The
238     /// returned guard also implements the [`Read`] and [`BufRead`] traits for
239     /// accessing the underlying data.
240     ///
241     /// [`Read`]: trait.Read.html
242     /// [`BufRead`]: trait.BufRead.html
243     #[stable(feature = "rust1", since = "1.0.0")]
244     pub fn lock(&self) -> StdinLock {
245         StdinLock { inner: self.inner.lock().unwrap_or_else(|e| e.into_inner()) }
246     }
247
248     /// Locks this handle and reads a line of input into the specified buffer.
249     ///
250     /// For detailed semantics of this method, see the documentation on
251     /// [`BufRead::read_line`].
252     ///
253     /// [`BufRead::read_line`]: trait.BufRead.html#method.read_line
254     ///
255     /// # Examples
256     ///
257     /// ```no_run
258     /// use std::io;
259     ///
260     /// let mut input = String::new();
261     /// match io::stdin().read_line(&mut input) {
262     ///     Ok(n) => {
263     ///         println!("{} bytes read", n);
264     ///         println!("{}", input);
265     ///     }
266     ///     Err(error) => println!("error: {}", error),
267     /// }
268     /// ```
269     ///
270     /// You can run the example one of two ways:
271     ///
272     /// - Pipe some text to it, e.g. `printf foo | path/to/executable`
273     /// - Give it text interactively by running the executable directly,
274     ///   in which case it will wait for the Enter key to be pressed before
275     ///   continuing
276     #[stable(feature = "rust1", since = "1.0.0")]
277     pub fn read_line(&self, buf: &mut String) -> io::Result<usize> {
278         self.lock().read_line(buf)
279     }
280 }
281
282 #[stable(feature = "rust1", since = "1.0.0")]
283 impl Read for Stdin {
284     fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
285         self.lock().read(buf)
286     }
287     fn read_to_end(&mut self, buf: &mut Vec<u8>) -> io::Result<usize> {
288         self.lock().read_to_end(buf)
289     }
290     fn read_to_string(&mut self, buf: &mut String) -> io::Result<usize> {
291         self.lock().read_to_string(buf)
292     }
293     fn read_exact(&mut self, buf: &mut [u8]) -> io::Result<()> {
294         self.lock().read_exact(buf)
295     }
296 }
297
298 #[stable(feature = "rust1", since = "1.0.0")]
299 impl<'a> Read for StdinLock<'a> {
300     fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
301         self.inner.read(buf)
302     }
303     fn read_to_end(&mut self, buf: &mut Vec<u8>) -> io::Result<usize> {
304         self.inner.read_to_end(buf)
305     }
306 }
307
308 #[stable(feature = "rust1", since = "1.0.0")]
309 impl<'a> BufRead for StdinLock<'a> {
310     fn fill_buf(&mut self) -> io::Result<&[u8]> { self.inner.fill_buf() }
311     fn consume(&mut self, n: usize) { self.inner.consume(n) }
312 }
313
314 /// A handle to the global standard output stream of the current process.
315 ///
316 /// Each handle shares a global buffer of data to be written to the standard
317 /// output stream. Access is also synchronized via a lock and explicit control
318 /// over locking is available via the `lock` method.
319 ///
320 /// Created by the [`io::stdout`] method.
321 ///
322 /// [`io::stdout`]: fn.stdout.html
323 #[stable(feature = "rust1", since = "1.0.0")]
324 pub struct Stdout {
325     // FIXME: this should be LineWriter or BufWriter depending on the state of
326     //        stdout (tty or not). Note that if this is not line buffered it
327     //        should also flush-on-panic or some form of flush-on-abort.
328     inner: Arc<ReentrantMutex<RefCell<LineWriter<Maybe<StdoutRaw>>>>>,
329 }
330
331 /// A locked reference to the `Stdout` handle.
332 ///
333 /// This handle implements the [`Write`] trait, and is constructed via
334 /// the [`Stdout::lock`] method.
335 ///
336 /// [`Write`]: trait.Write.html
337 /// [`Stdout::lock`]: struct.Stdout.html#method.lock
338 #[stable(feature = "rust1", since = "1.0.0")]
339 pub struct StdoutLock<'a> {
340     inner: ReentrantMutexGuard<'a, RefCell<LineWriter<Maybe<StdoutRaw>>>>,
341 }
342
343 /// Constructs a new handle to the standard output of the current process.
344 ///
345 /// Each handle returned is a reference to a shared global buffer whose access
346 /// is synchronized via a mutex. If you need more explicit control over
347 /// locking, see the [Stdout::lock] method.
348 ///
349 /// [Stdout::lock]: struct.Stdout.html#method.lock
350 ///
351 /// # Examples
352 ///
353 /// Using implicit synchronization:
354 ///
355 /// ```
356 /// use std::io::{self, Write};
357 ///
358 /// # fn foo() -> io::Result<()> {
359 /// try!(io::stdout().write(b"hello world"));
360 ///
361 /// # Ok(())
362 /// # }
363 /// ```
364 ///
365 /// Using explicit synchronization:
366 ///
367 /// ```
368 /// use std::io::{self, Write};
369 ///
370 /// # fn foo() -> io::Result<()> {
371 /// let stdout = io::stdout();
372 /// let mut handle = stdout.lock();
373 ///
374 /// try!(handle.write(b"hello world"));
375 ///
376 /// # Ok(())
377 /// # }
378 /// ```
379 #[stable(feature = "rust1", since = "1.0.0")]
380 pub fn stdout() -> Stdout {
381     static INSTANCE: Lazy<ReentrantMutex<RefCell<LineWriter<Maybe<StdoutRaw>>>>>
382         = Lazy::new(stdout_init);
383     return Stdout {
384         inner: INSTANCE.get().expect("cannot access stdout during shutdown"),
385     };
386
387     fn stdout_init() -> Arc<ReentrantMutex<RefCell<LineWriter<Maybe<StdoutRaw>>>>> {
388         let stdout = match stdout_raw() {
389             Ok(stdout) => Maybe::Real(stdout),
390             _ => Maybe::Fake,
391         };
392         Arc::new(ReentrantMutex::new(RefCell::new(LineWriter::new(stdout))))
393     }
394 }
395
396 impl Stdout {
397     /// Locks this handle to the standard output stream, returning a writable
398     /// guard.
399     ///
400     /// The lock is released when the returned lock goes out of scope. The
401     /// returned guard also implements the `Write` trait for writing data.
402     #[stable(feature = "rust1", since = "1.0.0")]
403     pub fn lock(&self) -> StdoutLock {
404         StdoutLock { inner: self.inner.lock().unwrap_or_else(|e| e.into_inner()) }
405     }
406 }
407
408 #[stable(feature = "rust1", since = "1.0.0")]
409 impl Write for Stdout {
410     fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
411         self.lock().write(buf)
412     }
413     fn flush(&mut self) -> io::Result<()> {
414         self.lock().flush()
415     }
416     fn write_all(&mut self, buf: &[u8]) -> io::Result<()> {
417         self.lock().write_all(buf)
418     }
419     fn write_fmt(&mut self, args: fmt::Arguments) -> io::Result<()> {
420         self.lock().write_fmt(args)
421     }
422 }
423 #[stable(feature = "rust1", since = "1.0.0")]
424 impl<'a> Write for StdoutLock<'a> {
425     fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
426         self.inner.borrow_mut().write(buf)
427     }
428     fn flush(&mut self) -> io::Result<()> {
429         self.inner.borrow_mut().flush()
430     }
431 }
432
433 /// A handle to the standard error stream of a process.
434 ///
435 /// For more information, see the [`io::stderr`] method.
436 ///
437 /// [`io::stderr`]: fn.stderr.html
438 #[stable(feature = "rust1", since = "1.0.0")]
439 pub struct Stderr {
440     inner: Arc<ReentrantMutex<RefCell<Maybe<StderrRaw>>>>,
441 }
442
443 /// A locked reference to the `Stderr` handle.
444 ///
445 /// This handle implements the `Write` trait and is constructed via
446 /// the [`Stderr::lock`] method.
447 ///
448 /// [`Stderr::lock`]: struct.Stderr.html#method.lock
449 #[stable(feature = "rust1", since = "1.0.0")]
450 pub struct StderrLock<'a> {
451     inner: ReentrantMutexGuard<'a, RefCell<Maybe<StderrRaw>>>,
452 }
453
454 /// Constructs a new handle to the standard error of the current process.
455 ///
456 /// This handle is not buffered.
457 ///
458 /// # Examples
459 ///
460 /// Using implicit synchronization:
461 ///
462 /// ```
463 /// use std::io::{self, Write};
464 ///
465 /// # fn foo() -> io::Result<()> {
466 /// try!(io::stderr().write(b"hello world"));
467 ///
468 /// # Ok(())
469 /// # }
470 /// ```
471 ///
472 /// Using explicit synchronization:
473 ///
474 /// ```
475 /// use std::io::{self, Write};
476 ///
477 /// # fn foo() -> io::Result<()> {
478 /// let stderr = io::stderr();
479 /// let mut handle = stderr.lock();
480 ///
481 /// try!(handle.write(b"hello world"));
482 ///
483 /// # Ok(())
484 /// # }
485 /// ```
486 #[stable(feature = "rust1", since = "1.0.0")]
487 pub fn stderr() -> Stderr {
488     static INSTANCE: Lazy<ReentrantMutex<RefCell<Maybe<StderrRaw>>>> = Lazy::new(stderr_init);
489     return Stderr {
490         inner: INSTANCE.get().expect("cannot access stderr during shutdown"),
491     };
492
493     fn stderr_init() -> Arc<ReentrantMutex<RefCell<Maybe<StderrRaw>>>> {
494         let stderr = match stderr_raw() {
495             Ok(stderr) => Maybe::Real(stderr),
496             _ => Maybe::Fake,
497         };
498         Arc::new(ReentrantMutex::new(RefCell::new(stderr)))
499     }
500 }
501
502 impl Stderr {
503     /// Locks this handle to the standard error stream, returning a writable
504     /// guard.
505     ///
506     /// The lock is released when the returned lock goes out of scope. The
507     /// returned guard also implements the `Write` trait for writing data.
508     #[stable(feature = "rust1", since = "1.0.0")]
509     pub fn lock(&self) -> StderrLock {
510         StderrLock { inner: self.inner.lock().unwrap_or_else(|e| e.into_inner()) }
511     }
512 }
513
514 #[stable(feature = "rust1", since = "1.0.0")]
515 impl Write for Stderr {
516     fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
517         self.lock().write(buf)
518     }
519     fn flush(&mut self) -> io::Result<()> {
520         self.lock().flush()
521     }
522     fn write_all(&mut self, buf: &[u8]) -> io::Result<()> {
523         self.lock().write_all(buf)
524     }
525     fn write_fmt(&mut self, args: fmt::Arguments) -> io::Result<()> {
526         self.lock().write_fmt(args)
527     }
528 }
529 #[stable(feature = "rust1", since = "1.0.0")]
530 impl<'a> Write for StderrLock<'a> {
531     fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
532         self.inner.borrow_mut().write(buf)
533     }
534     fn flush(&mut self) -> io::Result<()> {
535         self.inner.borrow_mut().flush()
536     }
537 }
538
539 /// Resets the thread-local stderr handle to the specified writer
540 ///
541 /// This will replace the current thread's stderr handle, returning the old
542 /// handle. All future calls to `panic!` and friends will emit their output to
543 /// this specified handle.
544 ///
545 /// Note that this does not need to be called for all new threads; the default
546 /// output handle is to the process's stderr stream.
547 #[unstable(feature = "set_stdio",
548            reason = "this function may disappear completely or be replaced \
549                      with a more general mechanism",
550            issue = "0")]
551 #[doc(hidden)]
552 pub fn set_panic(sink: Box<Write + Send>) -> Option<Box<Write + Send>> {
553     use panicking::LOCAL_STDERR;
554     use mem;
555     LOCAL_STDERR.with(move |slot| {
556         mem::replace(&mut *slot.borrow_mut(), Some(sink))
557     }).and_then(|mut s| {
558         let _ = s.flush();
559         Some(s)
560     })
561 }
562
563 /// Resets the thread-local stdout handle to the specified writer
564 ///
565 /// This will replace the current thread's stdout handle, returning the old
566 /// handle. All future calls to `print!` and friends will emit their output to
567 /// this specified handle.
568 ///
569 /// Note that this does not need to be called for all new threads; the default
570 /// output handle is to the process's stdout stream.
571 #[unstable(feature = "set_stdio",
572            reason = "this function may disappear completely or be replaced \
573                      with a more general mechanism",
574            issue = "0")]
575 #[doc(hidden)]
576 pub fn set_print(sink: Box<Write + Send>) -> Option<Box<Write + Send>> {
577     use mem;
578     LOCAL_STDOUT.with(move |slot| {
579         mem::replace(&mut *slot.borrow_mut(), Some(sink))
580     }).and_then(|mut s| {
581         let _ = s.flush();
582         Some(s)
583     })
584 }
585
586 #[unstable(feature = "print",
587            reason = "implementation detail which may disappear or be replaced at any time",
588            issue = "0")]
589 #[doc(hidden)]
590 pub fn _print(args: fmt::Arguments) {
591     // As an implementation of the `println!` macro, we want to try our best to
592     // not panic wherever possible and get the output somewhere. There are
593     // currently two possible vectors for panics we take care of here:
594     //
595     // 1. If the TLS key for the local stdout has been destroyed, accessing it
596     //    would cause a panic. Note that we just lump in the uninitialized case
597     //    here for convenience, we're not trying to avoid a panic.
598     // 2. If the local stdout is currently in use (e.g. we're in the middle of
599     //    already printing) then accessing again would cause a panic.
600     //
601     // If, however, the actual I/O causes an error, we do indeed panic.
602     let result = match LOCAL_STDOUT.state() {
603         LocalKeyState::Uninitialized |
604         LocalKeyState::Destroyed => stdout().write_fmt(args),
605         LocalKeyState::Valid => {
606             LOCAL_STDOUT.with(|s| {
607                 if s.borrow_state() == BorrowState::Unused {
608                     if let Some(w) = s.borrow_mut().as_mut() {
609                         return w.write_fmt(args);
610                     }
611                 }
612                 stdout().write_fmt(args)
613             })
614         }
615     };
616     if let Err(e) = result {
617         panic!("failed printing to stdout: {}", e);
618     }
619 }
620
621 #[cfg(test)]
622 mod tests {
623     use thread;
624     use super::*;
625
626     #[test]
627     fn panic_doesnt_poison() {
628         thread::spawn(|| {
629             let _a = stdin();
630             let _a = _a.lock();
631             let _a = stdout();
632             let _a = _a.lock();
633             let _a = stderr();
634             let _a = _a.lock();
635             panic!();
636         }).join().unwrap_err();
637
638         let _a = stdin();
639         let _a = _a.lock();
640         let _a = stdout();
641         let _a = _a.lock();
642         let _a = stderr();
643         let _a = _a.lock();
644     }
645 }