Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

use ParkingLot to construct WaitableMutex will crash #2238

Open
EdagrHW opened this issue Jun 15, 2024 · 0 comments
Open

use ParkingLot to construct WaitableMutex will crash #2238

EdagrHW opened this issue Jun 15, 2024 · 0 comments

Comments

@EdagrHW
Copy link

EdagrHW commented Jun 15, 2024

class WaitableMutex : public std::mutex {
    using Lot = ParkingLot<std::function<bool(void)>>;
    static Lot lot;

   public:
    void unlock() {
        bool unparked = false;
        lot.unpark(uint64_t(this), [&](std::function<bool(void)> wfunc) {
            if (wfunc()) {
                unparked = true;
                return UnparkControl::RemoveBreak;
            } else {
                return UnparkControl::RemoveContinue;
            }
        });

        if (!unparked) {
            std::mutex::unlock();
        }
    }

    template <typename Wait>
    void wait(Wait wfunc) {
        lot.park(
            uint64_t(this), wfunc, [&]() { return !wfunc(); }, [&]() { std::mutex::unlock(); });
    }
};

WaitableMutex::Lot WaitableMutex::lot;

int main() {
    // test();
    std::atomic<bool> go{false};
    WaitableMutex mu;
     std::thread t([&]() {
         std::unique_lock<WaitableMutex> g(mu);
         mu.wait([&]() { return go == true; });
     });
    std::this_thread::sleep_for(std::chrono::seconds(1));

    {
        std::lock_guard<WaitableMutex> g(mu);
        go = true;
    }
    t.join();
}
/*
error: unlock of unowned mutex
reason:
"When destructed twice, the unlock method will be called twice. The first time it will not execute std::mutex::unlock(), but the second time it will. And during the wait operation, std::mutex::unlock() has already been called once."
*/
@EdagrHW EdagrHW closed this as completed Jun 15, 2024
@EdagrHW EdagrHW reopened this Jun 15, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant