Fixed simpleclient crash caused by curResource being altered
authorErich Keane <erich.keane@intel.com>
Fri, 23 Jan 2015 23:21:36 +0000 (15:21 -0800)
committerSudarshan Prasad <sudarshan.prasad@intel.com>
Mon, 26 Jan 2015 00:05:54 +0000 (00:05 +0000)
The foundResource function is called asynchronously, and was written
in a way that was not thread safe. This fix adds a lock and exit logic
so that it works prooperly and only uses the first found curResource
that matches its requirements.

NOTE: This change (author: Erich Keane) is from 01.org.

Change-Id: I984ce1623ff491713ecf5d621f1283ebad33bfef
Signed-Off-by:Sudarshan Prasad<sudarshan.prasad@intel.com>
Signed-Off-by: Erich Keane <erich.keane@intel.com>
Reviewed-on: https://gerrit.iotivity.org/gerrit/236
Tested-by: jenkins-iotivity <jenkins-iotivity@opendaylight.org>
resource/examples/simpleclient.cpp

index b23c22ac2a366af3aceb31a189a6ec62141aea54..f4080d9961d7f76587b26227a070476461af5b74 100644 (file)
@@ -36,6 +36,7 @@ typedef std::map<OCResourceIdentifier, std::shared_ptr<OCResource>> DiscoveredRe
 DiscoveredResourceMap discoveredResources;
 std::shared_ptr<OCResource> curResource;
 static ObserveType OBSERVE_TYPE_TO_USE = ObserveType::Observe;
+std::mutex curResourceLock;
 
 class Light
 {
@@ -316,21 +317,24 @@ void foundResource(std::shared_ptr<OCResource> resource)
     std::string hostAddress;
     try
     {
-        if(discoveredResources.find(resource->uniqueIdentifier()) == discoveredResources.end())
         {
-            std::cout << "Found resource " << resource->uniqueIdentifier() <<
-                " for the first time on server with ID: "<< resource->sid()<<std::endl;
-            discoveredResources[resource->uniqueIdentifier()] = resource;
-        }
-        else
-        {
-            std::cout<<"Found resource "<< resource->uniqueIdentifier() << " again!"<<std::endl;
-        }
+            std::lock_guard<std::mutex> lock(curResourceLock);
+            if(discoveredResources.find(resource->uniqueIdentifier()) == discoveredResources.end())
+            {
+                std::cout << "Found resource " << resource->uniqueIdentifier() <<
+                    " for the first time on server with ID: "<< resource->sid()<<std::endl;
+                discoveredResources[resource->uniqueIdentifier()] = resource;
+            }
+            else
+            {
+                std::cout<<"Found resource "<< resource->uniqueIdentifier() << " again!"<<std::endl;
+            }
 
-        if(curResource)
-        {
-            std::cout << "Found another resource, ignoring"<<std::endl;
-            return;
+            if(curResource)
+            {
+                std::cout << "Found another resource, ignoring"<<std::endl;
+                return;
+            }
         }
 
         // Do some operations with resource object.