1 /*
2 * Copyright 2009-2017 Alibaba Cloud All rights reserved.
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 #include "ThreadExecutor.h"
18 #include <assert.h>
19 #include "../utils/LogUtils.h"
20 
21 using namespace AlibabaCloud::OSS;
22 
23 static const char *TAG = "ThreadExecutor";
24 
ThreadExecutor()25 ThreadExecutor::ThreadExecutor():
26     state_(State::Free)
27 {
28 }
29 
~ThreadExecutor()30 ThreadExecutor::~ThreadExecutor()
31 {
32     auto expected = State::Free;
33     while (!state_.compare_exchange_strong(expected, State::Shutdown))
34     {
35         assert(expected == State::Locked);
36         expected = State::Free;
37     }
38 
39     auto it = threads_.begin();
40     while (!threads_.empty())
41     {
42         it->second.join();
43         it = threads_.erase(it);
44     }
45 }
46 
execute(Runnable * task)47 void ThreadExecutor::execute(Runnable* task)
48 {
49     auto main = [task, this] {
50         OSS_LOG(LogLevel::LogDebug, TAG, "task(%p) enter execute main thread", task);
51         task->run();
52         delete task;
53         detach(std::this_thread::get_id());
54         OSS_LOG(LogLevel::LogDebug, TAG, "task(%p) leave execute main thread", task);
55     };
56 
57     State expected;
58     do
59     {
60         expected = State::Free;
61         if (state_.compare_exchange_strong(expected, State::Locked))
62         {
63             std::thread t(main);
64             const auto id = t.get_id();
65             threads_.emplace(id, std::move(t));
66             state_ = State::Free;
67             return;
68         }
69     } while (expected != State::Shutdown);
70     return;
71 }
72 
detach(std::thread::id id)73 void ThreadExecutor::detach(std::thread::id id)
74 {
75     State expected;
76     do
77     {
78         expected = State::Free;
79         if (state_.compare_exchange_strong(expected, State::Locked))
80         {
81             auto it = threads_.find(id);
82             assert(it != threads_.end());
83             it->second.detach();
84             threads_.erase(it);
85             state_ = State::Free;
86             return;
87         }
88     } while (expected != State::Shutdown);
89 }