Evniorment : Windows 7.0 , C++ , Multithreading

I have created a new worker thread to receive data on socket & add it into static multimap.
code snap :

       //remember mymultimap is static data type
       static std::multimap<string,string> mymultimap;
       EnterCriticalSection(&m_criticalsection); 
           mymultimap.insert ( "aaa", "bbb") );
       LeaveCriticalSection(&m_criticalsection);

At same time my main thread is reading same static multimap :
code snap :

        EnterCriticalSection(&m_criticalsection); 
        std::multimap<string,string>::iterator it = mymultimap.begin();
        for( ; it != mymultimap.end(); it++)
        {
            std::string firstName =  (*it).first;
            std::string secondName =  (*it).second;

        }
       LeaveCriticalSection(&m_criticalsection);

As main thread & work thread are continously doing read & write, it hamper by my application peformance.
Also static multimap contains huge data (more than 10,000 records).

How I can make thread lock for minmiual time in multimap.

EnterCriticalSection(&m_criticalsection); 
///minimal lock time for Map ???
LeaveCriticalSection(&m_criticalsection);

Please help me in improving application performance.

This sounds like it is a porblem caused by putting locks inside a loop without putting in anything that holds them up.

The thread reading from the socket should be held up by the socket comms, that is while it is not receiving any data it should not be trying to access the multimap.

Your main thread strictly has nothing to hold it up except that it only needs to process if there is something there to process. You need to use an extra object, a semaphore say. A semaphore is a sychronisation object that can be waited on that keeps a count, so every time the socket queue puts an entry in the multimap it posts to the semaphore and the main thread waits on the semaphore to be posted and then reads from the multimap.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.