]> git.meshlink.io Git - meshlink/blobdiff - src/meshlink.c
Use condition variables to wait for threads to finish initializing.
[meshlink] / src / meshlink.c
index 7e2e20e5c358b08b4ad7a57789055671cca3d626..20dad9f43caf437d15155931f2d528b3e1a30e42 100644 (file)
@@ -1382,16 +1382,16 @@ static void *meshlink_main_loop(void *arg) {
 #ifdef HAVE_SETNS
 
                if(setns(mesh->netns, CLONE_NEWNET) != 0) {
+                       pthread_cond_signal(&mesh->cond);
                        return NULL;
                }
 
 #else
+                       pthread_cond_signal(&mesh->cond);
                return NULL;
 #endif // HAVE_SETNS
        }
 
-       pthread_mutex_lock(&(mesh->mesh_mutex));
-
 #if HAVE_CATTA
 
        if(mesh->discovery) {
@@ -1400,10 +1400,15 @@ static void *meshlink_main_loop(void *arg) {
 
 #endif
 
+       pthread_mutex_lock(&(mesh->mesh_mutex));
+
        logger(mesh, MESHLINK_DEBUG, "Starting main_loop...\n");
+       pthread_cond_broadcast(&mesh->cond);
        main_loop(mesh);
        logger(mesh, MESHLINK_DEBUG, "main_loop returned.\n");
 
+       pthread_mutex_unlock(&(mesh->mesh_mutex));
+
 #if HAVE_CATTA
 
        // Stop discovery
@@ -1413,7 +1418,6 @@ static void *meshlink_main_loop(void *arg) {
 
 #endif
 
-       pthread_mutex_unlock(&(mesh->mesh_mutex));
        return NULL;
 }
 
@@ -1430,6 +1434,9 @@ bool meshlink_start(meshlink_handle_t *mesh) {
 
        pthread_mutex_lock(&(mesh->mesh_mutex));
 
+       assert(mesh->self->ecdsa);
+       assert(!memcmp((uint8_t *)mesh->self->ecdsa + 64, (uint8_t *)mesh->private_key + 64, 32));
+
        if(mesh->threadstarted) {
                logger(mesh, MESHLINK_DEBUG, "thread was already running\n");
                pthread_mutex_unlock(&(mesh->mesh_mutex));
@@ -1469,12 +1476,9 @@ bool meshlink_start(meshlink_handle_t *mesh) {
                return false;
        }
 
+       pthread_cond_wait(&mesh->cond, &mesh->mesh_mutex);
        mesh->threadstarted = true;
 
-       assert(mesh->self->ecdsa);
-       assert(!memcmp((uint8_t *)mesh->self->ecdsa + 64, (uint8_t *)mesh->private_key + 64, 32));
-
-
        pthread_mutex_unlock(&(mesh->mesh_mutex));
        return true;
 }