Skip to content
This repository was archived by the owner on Aug 8, 2023. It is now read-only.

Separate objects from Thread management - #1250

Merged
jfirebaugh merged 13 commits into
masterfrom
1250-separate-thread-object
Apr 16, 2015
Merged

jfirebaugh merged 13 commits into
masterfrom
1250-separate-thread-object

Conversation

@kkaefer

@kkaefer kkaefer commented Apr 10, 2015

Copy link
Copy Markdown
Member

We should separate objects like the SQLiteCache, DefaultFileSource and the Map object from thread management considerations.

kkaefer added 2 commits April 10, 2015 15:36
Thread<T> is a generic thread management object that starts a thread, creates an object T in that thread and calls its .start() function. When the Thread<T> object is destructed (which must happen in the thread that created it), it'll call the object's .stop() function, and wait for thread termination. The .stop() function must somehow get the thread to terminate. Note that object T's constructor/destructor/start()/stop() must be protected/private, and Thread<T> must be declared as a friend class. All public functions may be called from any thread and are exposed through operator->().

RunLoop encapsulates a libuv runloop and has a facility of dispatching function objects to the thread. It can be used either as a worker thread class by itself, or it can be derived from. This commit converts SQLiteCache to derive from RunLoop and removes the custom code used previously for managing the cache thread.
Adds more documentation, and guarantees that the Object in the managed thread stays around until the Thread<> destructor is called. This might happen if .start() returns before .stop() is called, e.g. when a run loop in Object() terminates prematurely.
@jfirebaugh

Copy link
Copy Markdown
Contributor

This is cool, I have an alternate factoring of these additions to suggest that I'll push up in a separate branch.

@jfirebaugh
jfirebaugh force-pushed the 1250-separate-thread-object branch from c8df336 to 3d166db Compare April 10, 2015 23:59
@jfirebaugh

Copy link
Copy Markdown
Contributor

@kkaefer - GCC 4.9 doesn't look like it's going to pan out. It produces:

In file included from ../../linux/main.cpp:10:0:
../../include/mbgl/util/thread.hpp: In constructor ‘mbgl::util::Thread<T>::Thread(Args&& ...) [with Args = {const char (&)[19]}; Object = mbgl::SQLiteCache]’:
../../include/mbgl/util/thread.hpp:40:1: internal compiler error: in gimple_expand_cfg, at cfgexpand.c:5658
 Thread<Object>::Thread(Args&&... args)
 ^

Also, installing the gcc-4.9 package breaks compilation with clang, due to a bug in clang (issue is for clang 3.5, but also exists in 3.4 apparently, which is what we're using).

@kkaefer
kkaefer force-pushed the 1250-separate-thread-object branch from 3d166db to 278e6bd Compare April 13, 2015 10:59
@jfirebaugh

Copy link
Copy Markdown
Contributor

The reason I prefer to merge Thread and RunLoop is it makes the interface safer -- you can enforce that the only access to the wrapped object is through invoke, and invoke can be defined in a way that permits only calling a member function on the thread, rather than arbitrary code with potential cross-thread lambda bindings. The member-function-based definition of invoke could also potentially support member functions with return values, automatically turning them into futures or callbacks.

@jfirebaugh

Copy link
Copy Markdown
Contributor

@kkaefer - I looked at this deeper this afternoon and I

  • Agree that Thread<> and RunLoop should stay separate.
  • See the need for access to the RunLoop from within Impl methods as closely related to the issue of transferring the result of a threaded function call back to the thread that the function call was invoked from. Closing the message-passing loop, essentially.
  • Still think that Thread<> should expose a "pointer-to-member-call only" invoke interface for maximum safety.

I think we can accomplish all of these simultaneously. I've pushed up a new implementation to more-separate that's close (hopefully) to complete. There are a few tricky templating issues that I haven't cracked, but I don't think they are insoluble.

Summary of changes vs. your branch:

  • RunLoop interface is streamlined and minimized. I removed the friend stuff and protected. RunLoop is now completely wrapped by Thread<>, so I don't think that's necessary.
  • Added:
    • A thread local RunLoop* current variable which holds the run loop for the current thread. (This is currently erroring; need to figure out how to enable the thread_local storage specifier or manually implement thread locality.)
    • A templated RunLoop::invoke overload which accepts a callback and invokes the callback on the invoking thread's RunLoop. This closes the loop of two evented threads doing message passing and is the key change.
  • Adjust Thread<> and users of it to this new mechanism.
    • Implement a "pointer-to-member-call only" Thread<>::invoke in terms of RunLoop::invoke.
    • Impl's return results directly rather than accepting a callback. See e.g. SQLiteCache::Impl::processGet.
    • Public interfaces use the callbacked version of Thread<>::invoke to obtain the result.

Then the remaining need for access to the underlying loop is only for doing other libuv things, and can be accomplished by adding a uv_loop_t* argument to the Impl methods that require it.

Let me know what you think, and if you can figure out how to fix the remaining compile errors.

@kkaefer

kkaefer commented Apr 14, 2015

Copy link
Copy Markdown
Member Author

This closes the loop of two evented threads doing message passing and is the key change.

Does that mean we can only invoke function on thread loops iff the current thread also has a runloop? That'd mean that we couldn't use the Thread<RunLoop> object for the Map thread, since the main thread which starts the Map thread doesn't have a RunLoop.

Impl's return results directly rather than accepting a callback. See e.g. SQLiteCache::Impl::processGet.

I like this change, much easier interface and we avoid all the errors with accidentally not calling the callback function. However, this also means that we can't pass on the callback if the current function can't satisfy the request; it essentially forces all invoke requests to be synchronous.

@kkaefer

kkaefer commented Apr 14, 2015

Copy link
Copy Markdown
Member Author

if you can figure out how to fix the remaining compile errors.

The underlying issue here is that it's really hard to forward & move the arguments correctly; std::bind produces something that is movable-only and that we can't convert to a std::function<>, since std::function<> requires copy-constructability.

@jfirebaugh

Copy link
Copy Markdown
Contributor

Does that mean we can only invoke function on thread loops iff the current thread also has a runloop?

It means we can invoke functions with a callback iff the current thread has a runloop. Fire-and-forget invocations are okay.

If we needed callbacks for the mean thread, we'd have to have some (platform-specific) means of dispatching on the native event loop of the main thread.

However, this also means that we can't pass on the callback if the current function can't satisfy the request; it essentially forces all invoke requests to be synchronous.

Not being able to pass on the callback directly is good -- the callback needs to be invoked on the invoking thread, and passing it on would hide this requirement.

Maybe we could define another overload for RunLoop::invoke/Thread<>::invoke that pass a wrapped callback:

// Invoke fn, passing a wrapper that invokes callback on the current run-loop
void RunLoop::invoke(std::function<void(Callback)>&& fn, Callback callback) {
        RunLoop& outer = *current.get();
        invoke(std::bind(fn, [&] () { outer.invoke(callback); }));
}

template <class Object>
template <class... Args>
void Thread<Object>::invoke(void (Object::*fn)(Args..., Callback), Args&&... args, Callback) {
    loop->invoke(std::bind(fn, object, ::std::forward<Args>(args)...), Callback);
}

void A::method(Callback callback) {
  thread->invoke(&A::method, callback);
}

void A::Impl::method(Callback callback) {
  asyncFunction(callback);
}

Not sure if that actually works though.

The underlying issue here is that it's really hard to forward & move the arguments correctly

Someone has to have solved the problem of generic cross-thread move semantics. I'll research this more today.

@jfirebaugh

Copy link
Copy Markdown
Contributor

Best reference so far: this article by Herb Sutter (this comment starts to touch on the problem we're facing).

@jfirebaugh

Copy link
Copy Markdown
Contributor

Asked a Stack Overflow question.

@tmpsantos

Copy link
Copy Markdown
Contributor

@jfirebaugh

Copy link
Copy Markdown
Contributor

So close! This is working if you compile in C++14 mode.

I should be able to replace these C++14 move-capturing lambdas with this trick but for some reason it doesn't work (runtime crash).

@springmeyer

Copy link
Copy Markdown
Contributor

I think @artemp and @kkaefer ruled this out, but its still worth mentioning that Fn&& fn looks like a "universal reference" to me. Which means it's not garunteed to be an rvalue: https://isocpp.org/blog/2012/11/universal-references-in-c11-scott-meyers

@jfirebaugh

Copy link
Copy Markdown
Contributor

This is how I would expect to be able to define invokeWithResult using pure C++11 and two instances of the move-capturing trick:

    // Invoke fn() in the runloop thread, then invoke callback(result) in the current thread.
    template <class Fn, class R>
    void invokeWithResult(Fn&& fn, std::function<void (R)> callback) {
        RunLoop* outer = current.get();
        invoke(std::bind([callback, outer] (Fn& fn_) {
            outer->invoke(std::bind([callback] (R& result) {
                callback(std::move(result));
            }, std::move(fn_())));
        }, std::move(fn)));
    }

But this fails to compile. The outer std::bind apparently winds up not having a eligible operator() template.

/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../include/c++/v1/functional:2084:9: note: candidate template ignored: substitution failure [with _Args = <>]: implicit instantiation of undefined template 'std::__1::__bind_return<(lambda at src/mbgl/util/run_loop.hpp:31:26), std::__1::tuple<std::__1::__bind<std::__1::unique_ptr<mbgl::Response, std::__1::default_delete<mbgl::Response> > (mbgl::SQLiteCache::Impl::*&)(const mbgl::Resource &), mbgl::SQLiteCache::Impl *&, const mbgl::Resource &> >, std::__1::tuple<>, false>'
        operator()(_Args&& ...__args)
        ^

@jfirebaugh

Copy link
Copy Markdown
Contributor

Looks like we don't need to move-capture there anyway. A copying capture works fine.

82c6bdb04d7ee426dd27f6303a3e3da6309ea214

@jfirebaugh
jfirebaugh force-pushed the 1250-separate-thread-object branch from f7f3bac to aa6edaa Compare April 16, 2015 01:27
@jfirebaugh

Copy link
Copy Markdown
Contributor

Storage tests are now failing because of an attempt to dispatch a result back to the main test thread, which doesn't have a run loop. Not sure how this used to work...

@jfirebaugh
jfirebaugh force-pushed the 1250-separate-thread-object branch from 67be25b to 708df31 Compare April 16, 2015 03:24
Implements a Thread<>::invoke interface that only permits calling
member functions with bound arguments.

Also introduce invokeWithResult, which accepts a callback and invokes
it, passing the result, on the invoking thread's RunLoop. This closes
the loop of two evented threads doing message passing.
@jfirebaugh
jfirebaugh force-pushed the 1250-separate-thread-object branch from 708df31 to ac25d32 Compare April 16, 2015 03:38
@jfirebaugh

Copy link
Copy Markdown
Contributor

@kkaefer You like?

I assume we'll convert the Map thread to this after merging #1065?

jfirebaugh added a commit that referenced this pull request Apr 16, 2015
Separate objects from Thread management
@jfirebaugh
jfirebaugh merged commit 7000a4f into master Apr 16, 2015
@jfirebaugh
jfirebaugh deleted the 1250-separate-thread-object branch April 16, 2015 15:50
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants