2013-11-13 05:16:10 +00:00
|
|
|
/*
|
|
|
|
Copyright (c) 2013 Microsoft Corporation. All rights reserved.
|
|
|
|
Released under Apache 2.0 license as described in the file LICENSE.
|
|
|
|
|
|
|
|
Author: Leonardo de Moura
|
|
|
|
*/
|
|
|
|
#pragma once
|
|
|
|
#include <atomic>
|
|
|
|
#include <thread>
|
|
|
|
#include <utility>
|
|
|
|
|
|
|
|
namespace lean {
|
|
|
|
/**
|
|
|
|
\brief Mark flag for interrupting current thread.
|
|
|
|
*/
|
|
|
|
void request_interrupt();
|
|
|
|
/**
|
|
|
|
\brief Reset (interrupt) flag for current thread.
|
|
|
|
*/
|
|
|
|
void reset_interrupt();
|
|
|
|
|
|
|
|
/**
|
|
|
|
\brief Return true iff the current thread was marked for interruption.
|
|
|
|
*/
|
2013-11-13 05:42:22 +00:00
|
|
|
bool interrupt_requested();
|
2013-11-13 05:16:10 +00:00
|
|
|
|
|
|
|
/**
|
2013-11-13 05:42:22 +00:00
|
|
|
\brief Throw an interrupted exception if the (interrupt) flag is set.
|
2013-11-13 05:16:10 +00:00
|
|
|
*/
|
2013-11-13 05:42:22 +00:00
|
|
|
void check_interrupted();
|
2013-11-13 05:16:10 +00:00
|
|
|
|
|
|
|
/**
|
|
|
|
\brief Thread that provides a method for setting its interrupt flag.
|
|
|
|
*/
|
|
|
|
class interruptible_thread {
|
|
|
|
std::atomic<std::atomic_bool*> m_flag_addr;
|
|
|
|
std::thread m_thread;
|
|
|
|
static std::atomic_bool * get_flag_addr();
|
|
|
|
public:
|
|
|
|
template<typename Function, typename... Args>
|
|
|
|
interruptible_thread(Function && fun, Args &&... args):
|
|
|
|
m_flag_addr(nullptr),
|
|
|
|
m_thread(
|
|
|
|
[&](Function&& fun, Args&&... args) {
|
|
|
|
m_flag_addr.store(get_flag_addr());
|
|
|
|
fun(std::forward<Args>(args)...);
|
|
|
|
},
|
|
|
|
std::forward<Function>(fun),
|
|
|
|
std::forward<Args>(args)...)
|
|
|
|
{}
|
|
|
|
|
|
|
|
/**
|
|
|
|
\brief Return true iff an interrupt request has been made to the current thread.
|
|
|
|
*/
|
|
|
|
bool interrupted() const;
|
|
|
|
/**
|
|
|
|
\brief Send a interrupt request to the current thread. Return
|
|
|
|
true iff the request has been successfully performed.
|
|
|
|
*/
|
|
|
|
bool request_interrupt();
|
|
|
|
|
|
|
|
void join();
|
|
|
|
bool joinable();
|
|
|
|
};
|
2013-11-15 03:06:36 +00:00
|
|
|
|
|
|
|
#ifdef LEAN_THREAD_UNSAFE
|
|
|
|
inline void check_threadsafe() {
|
|
|
|
throw exception("Lean was compiled without support for multi-threading");
|
|
|
|
}
|
|
|
|
#else
|
|
|
|
inline void check_threadsafe() {}
|
|
|
|
#endif
|
2013-11-13 05:16:10 +00:00
|
|
|
}
|