troubleshooting Question

C++ Object shared between 2 threads - how to synchronize it

Avatar of sriram
sriram asked on
Unix OSC++Algorithms
33 Comments2 Solutions1074 ViewsLast Modified:
Hello,
I create multiple threads. I know using static mutex locks we can synchronize threads accessing the data. My requirement is that if 2 threads simultaneously accessing a particular object should be locked otherwise no locks should apply.

In the example below, the main() creates a thread passing a pointer (handler1) to Class Handler. In this case accessing Send() method should be locked. if main() method is referring another class Handler object (handler2), both should be allowed to access Send() - if 2 threads share the common object pointer (handler1), then put a lock before Send() otherwise no locks.

class Handler
{
   public:

    virtual void Send()
    {
         // sending messages to socket stream
    }

  private:
     int _sock_fd;
};

void* thread_function(void* argObject)
{
    (Handler*)argObject->Send();
    return (void*)NULL;
}


main()
{
     Handler* handler1 = new Handler();

     // Test Case 1: In this scenario both main() and thread function are referring to same
     //                      handler1; therefore, should lock before accessing Send()

     pthread_t tid;
     int val = pthread_create(&tid, NULL, thread_function, (void*)handler1);
     handler1->Send();    



     // Test Case 2: In this scenario main() is accessing handler1 but thread function is
     //                      accessing handler2; therefore, should NOT apply lock before Send()

     Handler* handler2 = new Handler();
     pthread_t tid2;
     int val2= pthread_create(&tid2, NULL, thread_function, (void*)handler2);
     handler1->Send();
}

Thanks for the help
Join the community to see this answer!
Join our exclusive community to see this answer & millions of others.
Unlock 2 Answers and 33 Comments.
Join the Community
Learn from the best

Network and collaborate with thousands of CTOs, CISOs, and IT Pros rooting for you and your success.

Andrew Hancock - VMware vExpert
See if this solution works for you by signing up for a 7 day free trial.
Unlock 2 Answers and 33 Comments.
Try for 7 days

”The time we save is the biggest benefit of E-E to our team. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange.

-Mike Kapnisakis, Warner Bros