1 /* 2 * Copyright (c) 2021 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 "ecmascript/dfx/vm_thread_control.h" 17 18 namespace panda::ecmascript { 19 constexpr int32_t TIME_OUT_MS = 1500; 20 NotifyVMThreadSuspension()21bool VmThreadControl::NotifyVMThreadSuspension() // block caller thread 22 { 23 if (VMNeedSuspension()) { // only enable one thread to post suspension 24 return false; 25 } 26 SetVMNeedSuspension(true); 27 thread_->SetCheckSafePointStatus(); 28 os::memory::LockHolder lock(vmThreadSuspensionMutex_); 29 while (!IsSuspended()) { 30 if (vmThreadNeedSuspensionCV_.TimedWait(&vmThreadSuspensionMutex_, TIME_OUT_MS)) { 31 SetVMNeedSuspension(false); 32 thread_->ResetCheckSafePointStatus(); 33 return false; 34 } 35 } 36 return true; 37 } 38 SetVMNeedSuspension(bool flag)39void VmThreadControl::SetVMNeedSuspension(bool flag) 40 { 41 thread_->SetVMNeedSuspension(flag); 42 } 43 VMNeedSuspension() const44bool VmThreadControl::VMNeedSuspension() const 45 { 46 return thread_->VMNeedSuspension(); 47 } 48 SetVMSuspended(bool flag)49void VmThreadControl::SetVMSuspended(bool flag) 50 { 51 thread_->SetVMSuspended(flag); 52 } 53 IsSuspended() const54bool VmThreadControl::IsSuspended() const 55 { 56 return thread_->IsVMSuspended(); 57 } 58 SuspendVM()59void VmThreadControl::SuspendVM() // block vm thread 60 { 61 os::memory::LockHolder lock(vmThreadSuspensionMutex_); 62 SetVMSuspended(true); 63 vmThreadNeedSuspensionCV_.Signal(); // wake up the thread who needs suspend vmthread 64 while (VMNeedSuspension()) { 65 vmThreadHasSuspendedCV_.Wait(&vmThreadSuspensionMutex_); 66 } 67 SetVMSuspended(false); 68 } 69 ResumeVM()70void VmThreadControl::ResumeVM() 71 { 72 os::memory::LockHolder lock(vmThreadSuspensionMutex_); 73 SetVMNeedSuspension(false); 74 vmThreadHasSuspendedCV_.Signal(); 75 } 76 } // namespace panda::ecmascript