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#include "thread.h"
17
18#if defined(ENABLE_TASKPOOL_FFRT)
19#include "ffrt_inner.h"
20#include "c/executor_task.h"
21#endif
22#include "task_manager.h"
23
24namespace Commonlibrary::Concurrent::TaskPoolModule {
25Thread::Thread() : tid_() {}
26
27static constexpr uint64_t STACK_SIZE = 8 * 1024 * 1024;
28
29bool Thread::Start()
30{
31    if (TaskManager::GetInstance().EnableFfrt()) {
32#if defined(ENABLE_TASKPOOL_FFRT)
33        ffrt::task_attr task_attr;
34        (void)ffrt_task_attr_init(&task_attr);
35        ffrt_task_attr_set_name(&task_attr, "OS_TaskWorker");
36        ffrt_task_attr_set_qos(&task_attr, ffrt_qos_user_initiated);
37        ffrt_task_attr_set_local(&task_attr, true);
38        ffrt_task_attr_set_stack_size(&task_attr, STACK_SIZE);
39        auto task = [this]() {
40            Thread* thread = reinterpret_cast<Thread*>(this);
41            thread->Run();
42        };
43        ffrt::submit(task, {}, {}, task_attr);
44#endif
45        return 0;
46    } else {
47        int ret = uv_thread_create(&tid_, [](void* arg) {
48#if defined IOS_PLATFORM || defined MAC_PLATFORM
49            pthread_setname_np("OS_TaskWorker");
50#else
51            pthread_setname_np(pthread_self(), "OS_TaskWorker");
52#endif
53            Thread* thread = reinterpret_cast<Thread*>(arg);
54            thread->Run();
55        }, this);
56        return ret != 0;
57    }
58}
59}  // namespace Commonlibrary::Concurrent::TaskPoolModule