blob: 7015178f6c6aea9e723fedd26577551db76bc743 [file] [log] [blame]
Sean Paulcb8676c2015-05-13 06:22:10 -07001/*
2 * Copyright (C) 2015 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#ifndef ANDROID_WORKER_H_
18#define ANDROID_WORKER_H_
19
20#include <pthread.h>
Zach Reizner8467b122015-11-10 15:18:08 -080021#include <stdint.h>
Sean Paulcb8676c2015-05-13 06:22:10 -070022#include <string>
23
24namespace android {
25
26class Worker {
27 public:
28 int Lock();
29 int Unlock();
30
31 // Must be called with the lock acquired
32 int SignalLocked();
33 int ExitLocked();
34
35 // Convenience versions of above, acquires the lock
36 int Signal();
37 int Exit();
38
39 protected:
40 Worker(const char *name, int priority);
41 virtual ~Worker();
42
43 int InitWorker();
44
45 bool initialized() const;
46
47 virtual void Routine() = 0;
48
49 /*
Zach Reizner8467b122015-11-10 15:18:08 -080050 * Must be called with the lock acquired. max_nanoseconds may be negative to
51 * indicate infinite timeout, otherwise it indicates the maximum time span to
52 * wait for a signal before returning.
53 * Returns -EINTR if interrupted by exit request, or -ETIMEDOUT if timed out
Sean Paulcb8676c2015-05-13 06:22:10 -070054 */
Zach Reizner8467b122015-11-10 15:18:08 -080055 int WaitForSignalOrExitLocked(int64_t max_nanoseconds = -1);
Sean Paulcb8676c2015-05-13 06:22:10 -070056
57 private:
58 static void *InternalRoutine(void *worker);
59
60 // Must be called with the lock acquired
61 int SignalThreadLocked(bool exit);
62
63 std::string name_;
64 int priority_;
65
66 pthread_t thread_;
67 pthread_mutex_t lock_;
68 pthread_cond_t cond_;
69
70 bool exit_;
71 bool initialized_;
72};
73}
74
75#endif