vcl: set worker pthread stop key

Otherwise the key destructor is not called on pthread_exit.

Change-Id: I11e6b9683a926eecd3f40a44aab41924ff9c3101
Signed-off-by: Florin Coras <fcoras@cisco.com>
diff --git a/src/vcl/vcl_bapi.c b/src/vcl/vcl_bapi.c
index d702d7c..7d02c4f 100644
--- a/src/vcl/vcl_bapi.c
+++ b/src/vcl/vcl_bapi.c
@@ -155,6 +155,9 @@
 		    getpid (), mp->context, wrk_index);
       goto failed;
     }
+  if (!mp->is_add)
+    return;
+
   wrk = vcl_worker_get (wrk_index);
   wrk->app_event_queue = uword_to_pointer (mp->app_event_queue_address,
 					   svm_msg_q_t *);
diff --git a/src/vcl/vcl_private.c b/src/vcl/vcl_private.c
index ae4498e..0b8c2da 100644
--- a/src/vcl/vcl_private.c
+++ b/src/vcl/vcl_private.c
@@ -15,7 +15,7 @@
 
 #include <vcl/vcl_private.h>
 
-pthread_key_t vcl_worker_stop_key;
+static pthread_key_t vcl_worker_stop_key;
 
 static const char *
 vppcom_app_state_str (app_state_t state)
@@ -224,6 +224,7 @@
 vcl_worker_cleanup (void *arg)
 {
   vcl_worker_t *wrk = vcl_worker_get_current ();
+
   VDBG (0, "cleaning up worker %u", wrk->wrk_index);
   vcl_send_app_worker_add_del (0 /* is_add */ );
   close (wrk->mqs_epfd);
@@ -290,6 +291,9 @@
 
   if (pthread_key_create (&vcl_worker_stop_key, vcl_worker_cleanup))
     clib_warning ("failed to add pthread cleanup function");
+  if (pthread_setspecific (vcl_worker_stop_key, &wrk->thread_id))
+    clib_warning ("failed to setup key value");
+  wrk->thread_id = pthread_self ();
 
   clib_spinlock_unlock (&vcm->workers_lock);
 
diff --git a/src/vcl/vcl_private.h b/src/vcl/vcl_private.h
index 75f16ca..11d957a 100644
--- a/src/vcl/vcl_private.h
+++ b/src/vcl/vcl_private.h
@@ -257,6 +257,9 @@
 
   /** Vector acting as buffer for mq messages */
   svm_msg_q_msg_t *mq_msg_vector;
+
+  /** Used also as a thread stop key buffer */
+  pthread_t thread_id;
 } vcl_worker_t;
 
 typedef struct vppcom_main_t_
diff --git a/src/vnet/session/session_api.c b/src/vnet/session/session_api.c
index 6b72e7b..05b3bb8 100755
--- a/src/vnet/session/session_api.c
+++ b/src/vnet/session/session_api.c
@@ -1375,9 +1375,9 @@
 done:
   REPLY_MACRO2 (VL_API_APP_WORKER_ADD_DEL_REPLY, ({
     rmp->is_add = mp->is_add;
+    rmp->wrk_index = clib_host_to_net_u32 (args.wrk_index);
     if (!rv && mp->is_add)
       {
-	rmp->wrk_index = clib_host_to_net_u32 (args.wrk_index);
 	if (vec_len (args.segment->name))
 	  {
 	    memcpy (rmp->segment_name, args.segment->name,