andreiavrammsd / cpp-channel

Thread-safe container for sharing data between threads
https://blog.andreiavram.ro/cpp-channel-thread-safe-container-share-data-threads/
MIT License
415 stars 30 forks source link

Does not support `msd::channel<std::function<void()>>` #29

Closed leiless closed 1 year ago

leiless commented 1 year ago

It seems that msd::channel does not support function pointer.

[]() {} >> chan;
( []() {} ) >> chan;
andreiavrammsd commented 1 year ago

I never considered this. Is there a real use case to pass functions between threads?

leiless commented 1 year ago

I have a single socket fd, in which all the messages (request and response) should be done sequentially. So I want some callback to be passed to sequentia-lize between those messages.

Concurrent requests will cause the response to be out of order (byte streams).

andreiavrammsd commented 1 year ago

Understood. It will take me a while to find time for this. Please leave the issue open.

If it's urgent for you, I can only suggest to use a class in the channel (with dynamic polymorphism or std::variant) if it's suitable for you.

andreiavrammsd commented 1 year ago

This is because you try to push a lambda into a channel with type std::function<void()>. But the lambda does not have that type; it has a unique type.

You can assign a lambda to a std::function object.

using function_type = std::function<void()>;
msd::channel<function_type> channel;

const function_type func = []() {};
channel << func;

function_type out;
channel >> out;
out();

Does this help you?

andreiavrammsd commented 1 year ago

@leiless, have you tested this?

andreiavrammsd commented 1 year ago

When you test again, please come back if the proposed solution does not work.