FinnWilliamsArm | 4833cea | 2019-09-17 16:53:53 +0100 | [diff] [blame] | 1 | // |
| 2 | // Copyright © 2019 Arm Ltd. All rights reserved. |
| 3 | // SPDX-License-Identifier: MIT |
| 4 | // |
| 5 | |
| 6 | #include <atomic> |
| 7 | #include "CommandThread.hpp" |
| 8 | |
| 9 | namespace armnn |
| 10 | { |
| 11 | |
| 12 | namespace profiling |
| 13 | { |
| 14 | |
| 15 | CommandThread::CommandThread(uint32_t timeout, |
| 16 | bool stopAfterTimeout, |
| 17 | CommandHandlerRegistry& commandHandlerRegistry, |
| 18 | PacketVersionResolver& packetVersionResolver, |
| 19 | IProfilingConnection& socketProfilingConnection) |
| 20 | : m_Timeout(timeout) |
| 21 | , m_StopAfterTimeout(stopAfterTimeout) |
| 22 | , m_IsRunning(false) |
| 23 | , m_CommandHandlerRegistry(commandHandlerRegistry) |
| 24 | , m_PacketVersionResolver(packetVersionResolver) |
| 25 | , m_SocketProfilingConnection(socketProfilingConnection) |
| 26 | {}; |
| 27 | |
| 28 | void CommandThread::WaitForPacket() |
| 29 | { |
| 30 | do { |
| 31 | try |
| 32 | { |
| 33 | Packet packet = m_SocketProfilingConnection.ReadPacket(m_Timeout); |
| 34 | Version version = m_PacketVersionResolver.ResolvePacketVersion(packet.GetPacketId()); |
| 35 | |
| 36 | CommandHandlerFunctor* commandHandlerFunctor = |
| 37 | m_CommandHandlerRegistry.GetFunctor(packet.GetPacketId(), version.GetEncodedValue()); |
| 38 | commandHandlerFunctor->operator()(packet); |
| 39 | } |
| 40 | catch(armnn::TimeoutException) |
| 41 | { |
| 42 | if(m_StopAfterTimeout) |
| 43 | { |
| 44 | m_IsRunning.store(false, std::memory_order_relaxed); |
| 45 | return; |
| 46 | } |
| 47 | } |
| 48 | catch(...) |
| 49 | { |
| 50 | //might want to differentiate the errors more |
| 51 | m_IsRunning.store(false, std::memory_order_relaxed); |
| 52 | return; |
| 53 | } |
| 54 | |
| 55 | } while(m_KeepRunning.load(std::memory_order_relaxed)); |
| 56 | |
| 57 | m_IsRunning.store(false, std::memory_order_relaxed); |
| 58 | } |
| 59 | |
| 60 | void CommandThread::Start() |
| 61 | { |
| 62 | if (!m_CommandThread.joinable() && !IsRunning()) |
| 63 | { |
| 64 | m_IsRunning.store(true, std::memory_order_relaxed); |
| 65 | m_KeepRunning.store(true, std::memory_order_relaxed); |
| 66 | m_CommandThread = std::thread(&CommandThread::WaitForPacket, this); |
| 67 | } |
| 68 | } |
| 69 | |
| 70 | void CommandThread::Stop() |
| 71 | { |
| 72 | m_KeepRunning.store(false, std::memory_order_relaxed); |
| 73 | } |
| 74 | |
| 75 | void CommandThread::Join() |
| 76 | { |
| 77 | m_CommandThread.join(); |
| 78 | } |
| 79 | |
| 80 | bool CommandThread::IsRunning() const |
| 81 | { |
| 82 | return m_IsRunning.load(std::memory_order_relaxed); |
| 83 | } |
| 84 | |
| 85 | bool CommandThread::StopAfterTimeout(bool stopAfterTimeout) |
| 86 | { |
| 87 | if (!IsRunning()) |
| 88 | { |
| 89 | m_StopAfterTimeout = stopAfterTimeout; |
| 90 | return true; |
| 91 | } |
| 92 | return false; |
| 93 | } |
| 94 | |
| 95 | }//namespace profiling |
| 96 | |
| 97 | }//namespace armnn |