У меня есть класс-варпер для std :: thread. Вот конструктор:Использование std :: vector :: emplace_back
template <typename Function, typename... Args>
InterruptibleThread(Function&& fun, Args&&... args)
{
_thread = std::thread([](std::atomic_bool * f, Function&& function, Args&&... arguments)
{
_flag_ref = f;
(function)(std::forward<Args>(arguments)...);
},
&_flag,
std::forward<Function>(fun)
, std::forward<Args>(args)...
);
}
И тогда я использую его так (пример): InterruptibleThread (& SourceImageList :: StartFrameProcessingStatic, это, станд :: исх (он))
Компилятор сборках этот код успешно. Но сейчас я хотел бы сделать вектор таких объектов:
std::vector<InterruptibleThread> grp;
Я хотел бы передать его в стек так, что я делаю это:
grp.emplace_back(&SourceImageList::StartFrameProcessingStatic, this, std::ref(it));
И я получаю это ошибка:
C2064 term does not evaluate to a function taking 0 arguments
Вот варианты, которые проверяются компилятором:
1) grp.push_back(new InterruptibleThread(&SourceImageList::StartFrameProcessingStatic, this, std::ref(it)));
2) grp.push_back(InterruptibleThread(&SourceImageList::StartFrameProcessingStatic, this, std::ref(it)));
Но первый из них выделяет объект в куче, поэтому мне нужно отпустить его вручную, а второй - копию объекта.
Могу ли я использовать emplace_back
здесь (компилятор MSVC 2015 update 3)?
Update
Ok, я сделал некоторые исправления на основе ответов. Вот окончательный вариант этого класса:
#pragma once
#include <exception>
#include <atomic>
#include <thread>
#include <future>
#include <windows.h>
// Synopsis
class InterruptThreadException;
class InterruptibleThread;
// Interrupt exception
class InterruptThreadException : public virtual std::exception {
public:
virtual char const* what() const override { return "interrupt"; }
}; // class InterruptThreadException
// Interruptible thread
class InterruptibleThread {
public:
static void InterruptionPoint() noexcept(false) {
if (!InterruptibleThread::_flag_ref) { return; }
if (!InterruptibleThread::_flag_ref->load()) { return; }
throw InterruptThreadException();
} // check_for_interrupt
template <typename Function>
InterruptibleThread(Function&& fun) :
_thread([this, fun = std::move(std::forward<Function>(fun))]
{
_flag_ref = _flag.get();
fun();
})
{}
InterruptibleThread(InterruptibleThread&&) = default;
InterruptibleThread(const InterruptibleThread&) = delete;
bool Interrupting() const { return _flag->load(); }
void Interrupt() { _flag->store(true); }
void Join()
{
_thread.join();
}
bool TimedJoin(int msec)
{
return (std::async([=]() {Join(); }).wait_for(std::chrono::milliseconds(msec)) != std::future_status::timeout);
}
bool Joinable()
{
return _thread.joinable();
}
void Terminate()
{
TerminateThread(_thread.native_handle(), -1);
}
~InterruptibleThread()
{
if (_flag.get() != nullptr)
{
*_flag = false;
Interrupt();
}
if (_thread.joinable())
_thread.join()
}
private:
static thread_local std::atomic_bool* _flag_ref;
std::unique_ptr<std::atomic_bool> _flag = std::make_unique<std::atomic_bool>();
std::thread _thread;
};
И пример использования:
std::vector<InterruptibleThread> grp;
for (auto it : _sourceImages)
grp.emplace_back([this, it] {
it->StartFrameProcessing();
it->SetImageDelay(const_cast<EngineConfig*>(GetConfig())->ImageDelay);
});
"Могу ли я использовать emplace_back здесь" - вы * * попробовать?На самом деле просто попытка ответила бы на ваш вопрос. –
Вторая версия 'push_back', которую вы предоставили, должна фактически« перемещать »« ПрерываниеТребра »при возврате назад к вектору, а не в создании копии - компилятор почти наверняка будет использовать эту перегрузку. – ArchbishopOfBanterbury
@ArchbishopOfBanterbury В C++ 11 он определенно переместит его (поэтому компилятор не делает никакой дополнительной оптимизации), так как 'push_back' имеет перегрузку rvalue http://en.cppreference.com/w/cpp/container/ vector/push_back – vsoftco