winget-cli

Unnamed repository; edit this file 'description' to name the repository.
Log | Files | Refs | README | LICENSE

AppInstallerSynchronization.h (2067B)


      1 // Copyright (c) Microsoft Corporation.
      2 // Licensed under the MIT License.
      3 #pragma once
      4 #include <AppInstallerLanguageUtilities.h>
      5 #include <AppInstallerProgress.h>
      6 #include <wil/resource.h>
      7 
      8 #include <chrono>
      9 #include <functional>
     10 #include <string_view>
     11 #include <vector>
     12 
     13 using namespace std::chrono_literals;
     14 
     15 
     16 namespace AppInstaller::Synchronization
     17 {
     18     // This is a standard named mutex.
     19     // It must be acquired and released (or destroyed) on the same thread, just as all Windows mutexes must be.
     20     struct CrossProcessLock
     21     {
     22         CrossProcessLock(std::string_view name);
     23         CrossProcessLock(const std::wstring& name);
     24 
     25         ~CrossProcessLock();
     26 
     27         CrossProcessLock(const CrossProcessLock&) = delete;
     28         CrossProcessLock& operator=(const CrossProcessLock&) = delete;
     29 
     30         CrossProcessLock(CrossProcessLock&&) = default;
     31         CrossProcessLock& operator=(CrossProcessLock&&) = default;
     32 
     33         // Acquires the lock; cancellation is enabled via the progress object.
     34         // Returns true when the lock is acquired and false if the wait is cancelled.
     35         bool Acquire(IProgressCallback& progress);
     36 
     37         // Optionally release the lock before destroying the object.
     38         void Release();
     39 
     40         // Attempts to acquire the mutex without a wait.
     41         // Returns true if it was able, false if not.
     42         bool TryAcquireNoWait();
     43 
     44         // Indicates whether the lock is held.
     45         operator bool() const;
     46 
     47     private:
     48         wil::unique_mutex m_mutex;
     49         wil::mutex_release_scope_exit m_lock;
     50         DWORD m_lockThreadId = 0;
     51     };
     52 
     53     // This lock is used to prevent multiple winget related processes from attempting to install (or uninstall) at the same time.
     54     // It must be acquired and released (or destroyed) on the same thread, just as all Windows mutexes must be.
     55     struct CrossProcessInstallLock : public CrossProcessLock
     56     {
     57         CrossProcessInstallLock() : CrossProcessLock(L"WinGetCrossProcessInstallLock") {}
     58     };
     59 }