1 /*
2  * Copyright (c) 2022 Huawei Device Co., Ltd.
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at
6  *
7  *     http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15 
16 #ifndef JS_CONCURRENT_MODULE_WORKER_WORKER_RUNNER_H
17 #define JS_CONCURRENT_MODULE_WORKER_WORKER_RUNNER_H
18 
19 #include <functional>
20 
21 #include "native_engine/native_engine.h"
22 #include "thread.h"
23 
24 namespace Commonlibrary::Concurrent::WorkerModule {
25 struct WorkerStartCallback {
26     using CallbackFunction = std::function<void(void*)>;
27 
28     explicit WorkerStartCallback(CallbackFunction function = nullptr, void* dataArgs = nullptr)
29         : callback(function), data(dataArgs)
30     {}
31 
32     CallbackFunction callback;
33     void* data;
34 };
35 
36 class WorkerRunner {
37 public:
38     // real thread execute
39     class WorkerInnerRunner : public Thread {
40     public:
41         explicit WorkerInnerRunner(const WorkerRunner* runner);
42         ~WorkerInnerRunner() = default;
43         void Run() override;
44 
45     private:
46         const WorkerRunner* runner_;
47     };
48 
49     explicit WorkerRunner(WorkerStartCallback callback);
50     ~WorkerRunner();
51 
52     bool Execute();
53     void Run() const;
54     void Stop();
55 
56 private:
57     WorkerInnerRunner* workerInnerRunner_ {nullptr};
58     WorkerStartCallback callback_;
59     uv_thread_t selfThreadId_ {0};
60 };
61 } // namespace Commonlibrary::Concurrent::WorkerModule
62 #endif // JS_CONCURRENT_MODULE_WORKER_WORKER_RUNNER_H
63