ipc/android: Avoid race condition/blocking main thread

This commit is contained in:
Jarvis Huang 2021-11-29 16:55:35 +08:00 committed by Ryan Pavlik
parent f575a7a1a9
commit 3bb151e4bf
2 changed files with 5 additions and 11 deletions

View file

@ -65,6 +65,7 @@ public class MonadoImpl extends IMonado.Stub {
@Override
public void connect(@NotNull ParcelFileDescriptor parcelFileDescriptor) {
nativeWaitForServerStartup();
int fd = parcelFileDescriptor.getFd();
Log.i(TAG, "connect: given fd " + fd);
if (nativeAddClient(fd) != 0) {
@ -88,12 +89,7 @@ public class MonadoImpl extends IMonado.Stub {
return;
}
nativeAppSurface(surface);
startServerIfNeeded();
}
private void startServerIfNeeded() {
nativeStartServer();
nativeWaitForServerStartup();
}
@Override

View file

@ -58,6 +58,7 @@ private:
static struct ipc_server *server = NULL;
static IpcServerHelper *helper = nullptr;
static std::condition_variable helper_ready;
static std::unique_ptr<std::thread> server_thread{};
static std::mutex server_thread_mutex;
@ -79,9 +80,9 @@ Java_org_freedesktop_monado_ipc_MonadoImpl_nativeStartServer(JNIEnv *env, jobjec
std::unique_lock lock(server_thread_mutex);
if (!server && !server_thread) {
helper = new IpcServerHelper();
helper_ready.notify_all();
server_thread = std::make_unique<std::thread>(
[]() { ipc_server_main_android(&server, signalStartupCompleteTrampoline, helper); });
helper->waitForStartupComplete();
}
}
}
@ -89,11 +90,8 @@ Java_org_freedesktop_monado_ipc_MonadoImpl_nativeStartServer(JNIEnv *env, jobjec
extern "C" JNIEXPORT void JNICALL
Java_org_freedesktop_monado_ipc_MonadoImpl_nativeWaitForServerStartup(JNIEnv *env, jobject thiz)
{
if (server == nullptr) {
// Should not happen.
U_LOG_E("service: nativeWaitForServerStartup called before service started up!");
return;
}
std::unique_lock<std::mutex> lock(server_thread_mutex);
helper_ready.wait(lock, [&] { return helper != nullptr; });
helper->waitForStartupComplete();
}