The implementation of sleep() looks like a game of Seastar golf - doing something in the minimum number of lines possible :-) Unfortunately, it looks very clever, but not quite right. sleep() usually works correctly, but the sanitizer (in the debug build) catches a use after free. The problem was that we delete an object which contains a timer which contains the callback (and std::function) - from inside this callback. The workaround in this patch is to use our future chaining to only delete the sleeper object after its future became ready - and at that point, none of the sleeper object or code is needed any more. This patch also includes a regression test for this issue. The test looks silly (just sleeps and checks nothing), but in the debugging build it failed (with a sanitizer reporting use-after-free) before this patch. Signed-off-by: Nadav Har'El <nyh@cloudius-systems.com>
47 lines
1.4 KiB
C++
47 lines
1.4 KiB
C++
/*
|
|
* This file is open source software, licensed to you under the terms
|
|
* of the Apache License, Version 2.0 (the "License"). See the NOTICE file
|
|
* distributed with this work for additional information regarding copyright
|
|
* ownership. You may not use this file except in compliance with the License.
|
|
*
|
|
* You may obtain a copy of the License at
|
|
*
|
|
* http://www.apache.org/licenses/LICENSE-2.0
|
|
*
|
|
* Unless required by applicable law or agreed to in writing,
|
|
* software distributed under the License is distributed on an
|
|
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
|
* KIND, either express or implied. See the License for the
|
|
* specific language governing permissions and limitations
|
|
* under the License.
|
|
*/
|
|
|
|
/*
|
|
* Copyright (C) 2015 Cloudius Systems, Ltd.
|
|
*/
|
|
|
|
#pragma once
|
|
|
|
#include <chrono>
|
|
#include <functional>
|
|
|
|
#include "core/shared_ptr.hh"
|
|
#include "core/reactor.hh"
|
|
#include "core/future.hh"
|
|
|
|
template <typename Clock = std::chrono::high_resolution_clock, typename Rep, typename Period>
|
|
future<> sleep(std::chrono::duration<Rep, Period> dur) {
|
|
struct sleeper {
|
|
promise<> done;
|
|
timer<Clock> tmr;
|
|
sleeper(std::chrono::duration<Rep, Period> dur)
|
|
: tmr([this] { done.set_value(); })
|
|
{
|
|
tmr.arm(dur);
|
|
}
|
|
};
|
|
sleeper *s = new sleeper(dur);
|
|
future<> fut = s->done.get_future();
|
|
return fut.then([s] { delete s; });
|
|
}
|