Skip to content

Commit 637da63

Browse files
authored
Merge pull request #7 from dwd/co_thread
Co thread
2 parents eac8cac + b518d82 commit 637da63

11 files changed

Lines changed: 780 additions & 40 deletions

File tree

CMakeLists.txt

Lines changed: 39 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,48 @@
11
cmake_minimum_required(VERSION 3.13)
22
project(sigslot)
33

4-
set (CMAKE_CXX_STANDARD 20)
4+
# GoogleTest requires at least C++14, coroutines need C++20
5+
set(CMAKE_CXX_STANDARD 20)
6+
set(CMAKE_CXX_STANDARD_REQUIRED ON)
57

6-
include_directories(.)
7-
add_executable(example example.cc sigslot/sigslot.h)
8+
include(FetchContent)
9+
FetchContent_Declare(
10+
googletest
11+
URL https://github.com/google/googletest/archive/03597a01ee50ed33e9dfd640b249b4be3799d395.zip
12+
)
13+
FetchContent_MakeAvailable(googletest)
14+
15+
enable_testing()
16+
link_libraries(GTest::gtest_main)
17+
include_directories(${CMAKE_CURRENT_SOURCE_DIR})
18+
add_executable(sigslot-test
19+
test/sigslot.cc
20+
test/coroutine.cc
21+
sigslot/sigslot.h
22+
sigslot/tasklet.h
23+
sigslot/resume.h
24+
)
25+
add_executable(sigslot-test-resume
26+
sigslot/sigslot.h
27+
sigslot/tasklet.h
28+
test/resume.cc
29+
sigslot/resume.h
30+
)
31+
add_executable(sigslot-test-cothread
32+
sigslot/sigslot.h
33+
sigslot/tasklet.h
34+
test/cothread.cc
35+
sigslot/resume.h
36+
sigslot/cothread.h
37+
)
38+
include(GoogleTest)
39+
gtest_discover_tests(sigslot-test)
40+
gtest_discover_tests(sigslot-test-resume)
41+
gtest_discover_tests(sigslot-test-cothread)
842

9-
add_executable(co_example co_example.cc sigslot/sigslot.h)
1043
if (UNIX)
11-
target_compile_options(co_example PUBLIC -fcoroutines)
12-
target_link_options(co_example PUBLIC -fcoroutines)
44+
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fcoroutines")
1345
endif ()
1446
if (WIN32)
15-
target_compile_options(co_example PUBLIC /await)
47+
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /await")
1648
endif()
17-
target_compile_definitions(co_example PUBLIC -DSIGSLOT_COROUTINES)

README

Lines changed: 0 additions & 16 deletions
This file was deleted.

README.md

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
# sigslot - C++11 Signal/Slot library
2+
3+
Originally written by Sarah Thompson.
4+
5+
Various patches and fixes applied by Cat Nap Games:
6+
7+
To make this compile under Xcode 4.3 with Clang 3.0 I made some changes myself and also used some diffs published in the original project's Sourceforge forum.
8+
I don't remember which ones though.
9+
10+
C++11-erization (and C++2x-erixation, and mini coroutine library) by Dave Cridland:
11+
12+
See example.cc and co_example.cc for some documentation and a walk-through example, or read the tests.
13+
14+
This is public domain; no copyright is claimed or asserted.
15+
16+
No warranty is implied or offered either.
17+
18+
## Tagging and version
19+
20+
Until recently, I'd say just use HEAD. But some people are really keen on tags, so I'll do some semantic version tagging on this.
21+
22+
## Promising, yet oddly vague and sometimes outright misleading documentation
23+
24+
This library is a pure header library, and consists of four header files:
25+
26+
<sigslot/siglot.h>
27+
28+
This contains a sigslot::signal<T...> class, and a sigslot::has_slots class.
29+
30+
Signals can be connected to arbitrary functions, but in order to handle disconnect on lifetime termination, there's a "has_slots" base class to make it simpler.
31+
32+
Loosely, calling "emit(...)" on the signal will then call all the connected "slots", which are just arbitrary functions.
33+
34+
If a class is derived (publicly) from has_slots, you can pass in the instance of the class you want to control the lifetime. For calling a specific member directly, that's an easy decision; but if you pass in a lambda or some other arbitrary function, it might not be.
35+
36+
If there's nothing obvious to hand, something still needs to control the scope - leaving out the has_slots argument therefore returns you a (deliberately undocumented) placeholder class, which acts in lieu of a has_slots derived class of your choice.
37+
38+
<sigslot/tasklet.h>
39+
40+
This has a somewhat integrated coroutine library. Tasklets are coroutines, and like most coroutines they can be started, resumed, etc. There's no generator defined, just simple coroutines.
41+
42+
Tasklets expose co_await, so can be awaited by other coroutines. Signals can also be awaited upon, and will resolve to nothing (ie, void), or the single type, or a std::tuple of the types.
43+
44+
<sigslot/resume.h>
45+
46+
Coroutine resumption can be tricky, and is usually best integrated into some kind of event loop. Failure to do so will make it very hard to do anything that you couldn't do as well (or better!) without.
47+
48+
You can define your own resume function which will be called when a coroutine should be resumed, a trivial (and rather poor) example is at the beginning of the co_thread tests.
49+
50+
If you don't, then std::coroutine_handle<>::resume() will be called directly (which works for trivial cases, but not for anything useful).
51+
52+
<sigslot/cothread.h>
53+
54+
sigslot::co_thread is a convenient (but very simple) wrapper to run a non-coroutine in a std::jthread, but outwardly behave as a coroutine. Construct once, and it can be treated as a coroutine definition thereafter, and called multiple times.
55+
56+
This will not work with the built-in resumption, you'll need to implement *some* kind of event loop.

sigslot/cothread.h

Lines changed: 203 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,203 @@
1+
//
2+
// Created by dwd on 21/12/2021.
3+
//
4+
5+
#ifndef SIGSLOT_COTHREAD_H
6+
#define SIGSLOT_COTHREAD_H
7+
8+
#include <thread>
9+
#include "sigslot/sigslot.h"
10+
#include "sigslot/tasklet.h"
11+
12+
namespace sigslot {
13+
namespace cothread_internal {
14+
template<typename Result>
15+
struct awaitable {
16+
std::coroutine_handle<> awaiting = nullptr;
17+
18+
awaitable() = default;
19+
awaitable(awaitable && other) = delete;
20+
awaitable(awaitable const &) = delete;
21+
22+
bool await_ready() {
23+
return has_payload();
24+
}
25+
26+
void await_suspend(std::coroutine_handle<> h) {
27+
// The awaiting coroutine is already suspended.
28+
awaiting = h;
29+
await();
30+
}
31+
32+
auto await_resume() {
33+
return payload();
34+
}
35+
36+
void resolve() {
37+
std::coroutine_handle<> a = nullptr;
38+
std::swap(a, awaiting);
39+
if (a) sigslot::resume_switch(a);
40+
}
41+
42+
template<typename Fn, typename ...Args>
43+
void run(Fn & fn, Args&&... args) {
44+
auto wrapped_fn = [this, &fn](Args... a) {
45+
try {
46+
auto result = fn(a...);
47+
{
48+
std::lock_guard l_(m_mutex);
49+
m_payload.emplace(result);
50+
resolve();
51+
}
52+
} catch(...) {
53+
std::lock_guard l_(m_mutex);
54+
m_eptr = std::current_exception();
55+
resolve();
56+
}
57+
};
58+
m_thread.emplace(wrapped_fn, args...);
59+
}
60+
61+
void check_await() {
62+
if (!m_thread.has_value()) throw std::logic_error("No thread started");
63+
}
64+
65+
bool has_payload() {
66+
if (!m_thread.has_value()) throw std::logic_error("No thread started");
67+
std::lock_guard l_(m_mutex);
68+
return m_eptr || m_payload.has_value();
69+
}
70+
71+
auto payload() {
72+
if (!m_thread.has_value()) throw std::logic_error("No thread started");
73+
m_thread->join();
74+
m_thread.reset();
75+
if (m_eptr) std::rethrow_exception(m_eptr);
76+
return *m_payload;
77+
}
78+
79+
void await() {
80+
if (!m_thread.has_value()) throw std::logic_error("No thread started");
81+
std::lock_guard l_(m_mutex);
82+
if (m_eptr || m_payload.has_value()) {
83+
resolve();
84+
}
85+
}
86+
87+
private:
88+
std::optional<std::jthread> m_thread;
89+
std::optional<Result> m_payload;
90+
std::recursive_mutex m_mutex;
91+
std::exception_ptr m_eptr;
92+
};
93+
template<>
94+
struct awaitable<void> {
95+
std::coroutine_handle<> awaiting = nullptr;
96+
97+
awaitable() = default;
98+
awaitable(awaitable && other) = delete;
99+
awaitable(awaitable const &) = delete;
100+
101+
bool await_ready() {
102+
return is_done();
103+
}
104+
105+
void await_suspend(std::coroutine_handle<> h) {
106+
// The awaiting coroutine is already suspended.
107+
awaiting = h;
108+
await();
109+
}
110+
111+
void await_resume() {
112+
done();
113+
}
114+
115+
void resolve() {
116+
std::coroutine_handle<> a = nullptr;
117+
std::swap(a, awaiting);
118+
if (a) sigslot::resume_switch(a);
119+
}
120+
121+
template<typename Fn, typename ...Args>
122+
void run(Fn & fn, Args&&... args) {
123+
auto wrapped_fn = [this, &fn](Args... a) {
124+
try {
125+
fn(a...);
126+
{
127+
std::lock_guard l_(m_mutex);
128+
m_done = true;
129+
resolve();
130+
}
131+
} catch(...) {
132+
std::lock_guard l_(m_mutex);
133+
m_eptr = std::current_exception();
134+
resolve();
135+
}
136+
};
137+
m_thread.emplace(wrapped_fn, args...);
138+
}
139+
140+
void check_await() {
141+
if (!m_thread.has_value()) throw std::logic_error("No thread started");
142+
}
143+
144+
bool is_done() {
145+
if (!m_thread.has_value()) throw std::logic_error("No thread started");
146+
std::lock_guard l_(m_mutex);
147+
return m_eptr || m_done;
148+
}
149+
150+
void done() {
151+
if (!m_thread.has_value()) throw std::logic_error("No thread started");
152+
m_thread->join();
153+
m_thread.reset();
154+
if (m_eptr) std::rethrow_exception(m_eptr);
155+
}
156+
157+
void await() {
158+
if (!m_thread.has_value()) throw std::logic_error("No thread started");
159+
std::lock_guard l_(m_mutex);
160+
if (m_eptr || m_done) {
161+
resolve();
162+
}
163+
}
164+
165+
private:
166+
std::optional<std::jthread> m_thread;
167+
bool m_done = false;
168+
std::exception_ptr m_eptr;
169+
std::recursive_mutex m_mutex;
170+
};
171+
template<typename T>
172+
struct awaitable_ptr {
173+
std::unique_ptr<awaitable<T>> m_guts;
174+
175+
awaitable_ptr() : m_guts(std::make_unique<awaitable<T>>()) {}
176+
awaitable_ptr(awaitable_ptr &&) = default;
177+
178+
awaitable<T> & operator co_await() {
179+
m_guts->check_await();
180+
return *m_guts;
181+
}
182+
};
183+
}
184+
185+
template<typename Callable>
186+
class co_thread {
187+
public:
188+
private:
189+
Callable m_fn;
190+
public:
191+
192+
template<typename ...Args>
193+
[[nodiscard]] auto operator() (Args && ...args) {
194+
cothread_internal::awaitable_ptr<decltype(m_fn(args...))> awaitable;
195+
awaitable.m_guts->run(m_fn, args...);
196+
return std::move(awaitable);
197+
}
198+
199+
explicit co_thread(Callable && fn) : m_fn(std::move(fn)) {}
200+
};
201+
}
202+
203+
#endif

sigslot/resume.h

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
//
2+
// Created by dave on 22/07/2024.
3+
//
4+
5+
#ifndef SIGSLOT_RESUME_H
6+
#define SIGSLOT_RESUME_H
7+
8+
#ifndef SIGSLOT_NO_COROUTINES
9+
#include <coroutine>
10+
11+
namespace sigslot {
12+
namespace coroutines {
13+
struct sentinel {};
14+
}
15+
coroutines::sentinel resume(...);
16+
}
17+
#endif
18+
19+
#endif //SIGSLOT_RESUME_H

0 commit comments

Comments
 (0)