xref: /aosp_15_r20/external/cronet/base/test/test_io_thread.h (revision 6777b5387eb2ff775bb5750e3f5d96f37fb7352b)
1 // Copyright 2013 The Chromium Authors
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 #ifndef BASE_TEST_TEST_IO_THREAD_H_
6 #define BASE_TEST_TEST_IO_THREAD_H_
7 
8 #include "base/compiler_specific.h"
9 #include "base/functional/callback_forward.h"
10 #include "base/memory/ref_counted.h"
11 #include "base/task/task_runner.h"
12 #include "base/threading/thread.h"
13 
14 namespace base {
15 
16 // Create and run an IO thread with a MessageLoop, and
17 // making the MessageLoop accessible from its client.
18 // It also provides some ideomatic API like PostTaskAndWait().
19 //
20 // This API is not thread-safe:
21 //   - Start()/Stop() should only be called from the main (creation) thread.
22 //   - PostTask()/message_loop()/task_runner() are also safe to call from the
23 //     underlying thread itself (to post tasks from other threads: get the
24 //     task_runner() from the main thread first, it is then safe to pass _it_
25 //     around).
26 class TestIOThread {
27  public:
28   enum Mode { kAutoStart, kManualStart };
29   explicit TestIOThread(Mode mode);
30 
31   TestIOThread(const TestIOThread&) = delete;
32   TestIOThread& operator=(const TestIOThread&) = delete;
33 
34   // Stops the I/O thread if necessary.
35   ~TestIOThread();
36 
37   // After Stop(), Start() may be called again to start a new I/O thread.
38   // Stop() may be called even when the I/O thread is not started.
39   void Start();
40   void Stop();
41 
42   // Post |task| to the IO thread.
43   void PostTask(const Location& from_here, base::OnceClosure task);
44 
task_runner()45   scoped_refptr<SingleThreadTaskRunner> task_runner() {
46     return io_thread_.task_runner();
47   }
48 
49  private:
50   base::Thread io_thread_;
51   bool io_thread_started_;
52 };
53 
54 }  // namespace base
55 
56 #endif  // BASE_TEST_TEST_IO_THREAD_H_
57