| 1 | // Copyright (C) Microsoft Corporation. All rights reserved. |
| 2 | #pragma once |
| 3 | |
| 4 | #include "p9platform.h" |
| 5 | #include "p9ihandler.h" |
| 6 | |
| 7 | namespace p9fs { |
| 8 | |
| 9 | // This class is basically a countdown event for active connections. |
| 10 | class WaitGroup |
| 11 | { |
| 12 | public: |
| 13 | // Add a new wait group member. This should only be called by HandleConnections. |
| 14 | auto Add() |
| 15 | { |
| 16 | ++m_Count; |
| 17 | return std::unique_ptr<WaitGroup, Deleter>{this}; |
| 18 | } |
| 19 | |
| 20 | // Wait until all members are done. This should only be called by HandleConnections. |
| 21 | Task<void> Wait() |
| 22 | { |
| 23 | Done(); |
| 24 | co_await m_Event; |
| 25 | } |
| 26 | |
| 27 | // Check if there are members. |
| 28 | // N.B. The primary member (which is released by HandleConnections when the cancel token is |
| 29 | // canceled), is not counted. |
| 30 | // N.B. This is the only member the caller of HandleConnections may use. |
| 31 | bool HasMembers() const noexcept |
| 32 | { |
| 33 | return m_Count > 1; |
| 34 | } |
| 35 | |
| 36 | private: |
| 37 | void Done() |
| 38 | { |
| 39 | if (--m_Count == 0) |
| 40 | { |
| 41 | m_Event.Set(); |
| 42 | } |
| 43 | } |
| 44 | |
| 45 | struct Deleter |
| 46 | { |
| 47 | void operator()(WaitGroup* group) const |
| 48 | { |
| 49 | group->Done(); |
| 50 | } |
| 51 | }; |
| 52 | |
| 53 | AsyncEvent m_Event; |
| 54 | std::atomic<ULONG_PTR> m_Count{1}; |
| 55 | }; |
| 56 | |
| 57 | AsyncTask HandleConnections(ISocket& listen, IShareList& shareList, CancelToken& token, WaitGroup& waitGroup); |
| 58 | |
| 59 | } // namespace p9fs |