Luanti 5.10.0-dev
 
Loading...
Searching...
No Matches
lambda.h
Go to the documentation of this file.
1// Minetest
2// SPDX-License-Identifier: LGPL-2.1-or-later
3
4#pragma once
5
6#include <exception>
7#include <functional>
8#include <memory>
9#include "debug.h"
10#include "threading/thread.h"
11
17class LambdaThread : public Thread
18{
19 friend std::unique_ptr<LambdaThread> runInThread(
20 const std::function<void()> &, const std::string &);
21public:
23 void rethrow()
24 {
26 if (m_exptr)
27 std::rethrow_exception(m_exptr);
28 }
29
30private:
31 // hide methods
32 LambdaThread(const std::string &name="") : Thread(name) {}
33 using Thread::start;
34
35 std::function<void()> m_fn;
36 std::exception_ptr m_exptr;
37
38 void *run()
39 {
40 try {
41 m_fn();
42 } catch(...) {
43 m_exptr = std::current_exception();
44 }
45 return nullptr;
46 };
47};
48
57std::unique_ptr<LambdaThread> runInThread(const std::function<void()> &fn,
58 const std::string &thread_name = "")
59{
60 std::unique_ptr<LambdaThread> t(new LambdaThread(thread_name));
61 t->m_fn = fn;
62 t->start();
63 return t;
64}
Class returned by runInThread.
Definition lambda.h:18
friend std::unique_ptr< LambdaThread > runInThread(const std::function< void()> &, const std::string &)
Run a lambda in a separate thread.
Definition lambda.h:57
void * run()
Definition lambda.h:38
LambdaThread(const std::string &name="")
Definition lambda.h:32
std::exception_ptr m_exptr
Definition lambda.h:36
std::function< void()> m_fn
Definition lambda.h:35
void rethrow()
Re-throw a caught exception, if any. Can only be called after thread exit.
Definition lambda.h:23
Definition thread.h:57
bool isRunning()
Definition thread.h:91
bool start()
Definition thread.cpp:109
#define sanity_check(expr)
Definition debug.h:56
std::unique_ptr< LambdaThread > runInThread(const std::function< void()> &fn, const std::string &thread_name="")
Run a lambda in a separate thread.
Definition lambda.h:57