Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Co thread #7

Merged
merged 4 commits into from
Jul 24, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
47 changes: 39 additions & 8 deletions CMakeLists.txt
Original file line number Diff line number Diff line change
@@ -1,17 +1,48 @@
cmake_minimum_required(VERSION 3.13)
project(sigslot)

set (CMAKE_CXX_STANDARD 20)
# GoogleTest requires at least C++14, coroutines need C++20
set(CMAKE_CXX_STANDARD 20)
set(CMAKE_CXX_STANDARD_REQUIRED ON)

include_directories(.)
add_executable(example example.cc sigslot/sigslot.h)
include(FetchContent)
FetchContent_Declare(
googletest
URL https://github.com/google/googletest/archive/03597a01ee50ed33e9dfd640b249b4be3799d395.zip
)
FetchContent_MakeAvailable(googletest)

enable_testing()
link_libraries(GTest::gtest_main)
include_directories(${CMAKE_CURRENT_SOURCE_DIR})
add_executable(sigslot-test
test/sigslot.cc
test/coroutine.cc
sigslot/sigslot.h
sigslot/tasklet.h
sigslot/resume.h
)
add_executable(sigslot-test-resume
sigslot/sigslot.h
sigslot/tasklet.h
test/resume.cc
sigslot/resume.h
)
add_executable(sigslot-test-cothread
sigslot/sigslot.h
sigslot/tasklet.h
test/cothread.cc
sigslot/resume.h
sigslot/cothread.h
)
include(GoogleTest)
gtest_discover_tests(sigslot-test)
gtest_discover_tests(sigslot-test-resume)
gtest_discover_tests(sigslot-test-cothread)

add_executable(co_example co_example.cc sigslot/sigslot.h)
if (UNIX)
target_compile_options(co_example PUBLIC -fcoroutines)
target_link_options(co_example PUBLIC -fcoroutines)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fcoroutines")
endif ()
if (WIN32)
target_compile_options(co_example PUBLIC /await)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /await")
endif()
target_compile_definitions(co_example PUBLIC -DSIGSLOT_COROUTINES)
16 changes: 0 additions & 16 deletions README

This file was deleted.

56 changes: 56 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
# sigslot - C++11 Signal/Slot library

Originally written by Sarah Thompson.

Various patches and fixes applied by Cat Nap Games:

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.
I don't remember which ones though.

C++11-erization (and C++2x-erixation, and mini coroutine library) by Dave Cridland:

See example.cc and co_example.cc for some documentation and a walk-through example, or read the tests.

This is public domain; no copyright is claimed or asserted.

No warranty is implied or offered either.

## Tagging and version

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.

## Promising, yet oddly vague and sometimes outright misleading documentation

This library is a pure header library, and consists of four header files:

<sigslot/siglot.h>

This contains a sigslot::signal<T...> class, and a sigslot::has_slots class.

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.

Loosely, calling "emit(...)" on the signal will then call all the connected "slots", which are just arbitrary functions.

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.

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.

<sigslot/tasklet.h>

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.

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.

<sigslot/resume.h>

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.

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.

If you don't, then std::coroutine_handle<>::resume() will be called directly (which works for trivial cases, but not for anything useful).

<sigslot/cothread.h>

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.

This will not work with the built-in resumption, you'll need to implement *some* kind of event loop.
203 changes: 203 additions & 0 deletions sigslot/cothread.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,203 @@
//
// Created by dwd on 21/12/2021.
//

#ifndef SIGSLOT_COTHREAD_H
#define SIGSLOT_COTHREAD_H

#include <thread>
#include "sigslot/sigslot.h"
#include "sigslot/tasklet.h"

namespace sigslot {
namespace cothread_internal {
template<typename Result>
struct awaitable {
std::coroutine_handle<> awaiting = nullptr;

awaitable() = default;
awaitable(awaitable && other) = delete;
awaitable(awaitable const &) = delete;

bool await_ready() {
return has_payload();
}

void await_suspend(std::coroutine_handle<> h) {
// The awaiting coroutine is already suspended.
awaiting = h;
await();
}

auto await_resume() {
return payload();
}

void resolve() {
std::coroutine_handle<> a = nullptr;
std::swap(a, awaiting);
if (a) sigslot::resume_switch(a);
}

template<typename Fn, typename ...Args>
void run(Fn & fn, Args&&... args) {
auto wrapped_fn = [this, &fn](Args... a) {
try {
auto result = fn(a...);
{
std::lock_guard l_(m_mutex);
m_payload.emplace(result);
resolve();
}
} catch(...) {
std::lock_guard l_(m_mutex);
m_eptr = std::current_exception();
resolve();
}
};
m_thread.emplace(wrapped_fn, args...);
}

void check_await() {
if (!m_thread.has_value()) throw std::logic_error("No thread started");
}

bool has_payload() {
if (!m_thread.has_value()) throw std::logic_error("No thread started");
std::lock_guard l_(m_mutex);
return m_eptr || m_payload.has_value();
}

auto payload() {
if (!m_thread.has_value()) throw std::logic_error("No thread started");
m_thread->join();
m_thread.reset();
if (m_eptr) std::rethrow_exception(m_eptr);
return *m_payload;
}

void await() {
if (!m_thread.has_value()) throw std::logic_error("No thread started");
std::lock_guard l_(m_mutex);
if (m_eptr || m_payload.has_value()) {
resolve();
}
}

private:
std::optional<std::jthread> m_thread;
std::optional<Result> m_payload;
std::recursive_mutex m_mutex;
std::exception_ptr m_eptr;
};
template<>
struct awaitable<void> {
std::coroutine_handle<> awaiting = nullptr;

awaitable() = default;
awaitable(awaitable && other) = delete;
awaitable(awaitable const &) = delete;

bool await_ready() {
return is_done();
}

void await_suspend(std::coroutine_handle<> h) {
// The awaiting coroutine is already suspended.
awaiting = h;
await();
}

void await_resume() {
done();
}

void resolve() {
std::coroutine_handle<> a = nullptr;
std::swap(a, awaiting);
if (a) sigslot::resume_switch(a);
}

template<typename Fn, typename ...Args>
void run(Fn & fn, Args&&... args) {
auto wrapped_fn = [this, &fn](Args... a) {
try {
fn(a...);
{
std::lock_guard l_(m_mutex);
m_done = true;
resolve();
}
} catch(...) {
std::lock_guard l_(m_mutex);
m_eptr = std::current_exception();
resolve();
}
};
m_thread.emplace(wrapped_fn, args...);
}

void check_await() {
if (!m_thread.has_value()) throw std::logic_error("No thread started");
}

bool is_done() {
if (!m_thread.has_value()) throw std::logic_error("No thread started");
std::lock_guard l_(m_mutex);
return m_eptr || m_done;
}

void done() {
if (!m_thread.has_value()) throw std::logic_error("No thread started");
m_thread->join();
m_thread.reset();
if (m_eptr) std::rethrow_exception(m_eptr);
}

void await() {
if (!m_thread.has_value()) throw std::logic_error("No thread started");
std::lock_guard l_(m_mutex);
if (m_eptr || m_done) {
resolve();
}
}

private:
std::optional<std::jthread> m_thread;
bool m_done = false;
std::exception_ptr m_eptr;
std::recursive_mutex m_mutex;
};
template<typename T>
struct awaitable_ptr {
std::unique_ptr<awaitable<T>> m_guts;

awaitable_ptr() : m_guts(std::make_unique<awaitable<T>>()) {}
awaitable_ptr(awaitable_ptr &&) = default;

awaitable<T> & operator co_await() {
m_guts->check_await();
return *m_guts;
}
};
}

template<typename Callable>
class co_thread {
public:
private:
Callable m_fn;
public:

template<typename ...Args>
[[nodiscard]] auto operator() (Args && ...args) {
cothread_internal::awaitable_ptr<decltype(m_fn(args...))> awaitable;
awaitable.m_guts->run(m_fn, args...);
return std::move(awaitable);
}

explicit co_thread(Callable && fn) : m_fn(std::move(fn)) {}
};
}

#endif
19 changes: 19 additions & 0 deletions sigslot/resume.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
//
// Created by dave on 22/07/2024.
//

#ifndef SIGSLOT_RESUME_H
#define SIGSLOT_RESUME_H

#ifndef SIGSLOT_NO_COROUTINES
#include <coroutine>

namespace sigslot {
namespace coroutines {
struct sentinel {};
}
coroutines::sentinel resume(...);
}
#endif

#endif //SIGSLOT_RESUME_H
Loading