mardi 10 août 2021

Is this approach correct ? Limiting a specific no of threads to access a method for a specific time interval

I currently have multiple threads about (80) which are trying to access a specific method. The method basically determines whether these threads are allowed to perform a task or not.

The objective of the function is to allow 10 threads at a time to perform a task.After a specific time interval the function allows a set of other 10 threads that were waiting in line to perform a task. This is how I am accomplishing this

bool DoWork(UINT64 quantity, UINT64 threadIndex) //quantity = 10
{
    {
        std::lock_guard<std::mutex> guard(mymutex);

        bool result = false;

        long int elapsedLimit = 10 ; //10 milliseconds

        if (TimeStarted == 0)   //This is ULONGLONG
        {
            TimeStarted = GetTickCount64();
        }

        TimeEnded = GetTickCount64();

        if ( (TimeEnded - TimeStarted) > elapsedLimit)
        {
            //Time has elapsed. Lets reset the std::set and take new contestants
            m_storage.clear(); //this is std::set<UINT64> m_storage;
            TimeStarted = TimeEnded;
            return false;
        }
        else
        {
            //Check if we have slot in our set
            if (m_storage.size() < quantity)
            {
                m_storage.insert(threadIndex);
                return true;
            }
            else
            {
                //Check if this thread is already in the list
                if (m_storage.find(threadIndex) != m_storage.end()) 
                {
                   
                    result = true;
                }
                else 
                {
                    result = false;
                }
            }
        }
       
        return result;
    }
}

The way this is being accomplished is that initially the function checks to see if a specific thread is in a std::set. If it is then the caller function gets back a true otherwise the function checks if the set has less than 10 items in it if so then the function adds the id of that thread into the set and still returns a true. If the set is at full capacity which is 10 then it returns back a false. If the time elapsed is more than 10 ms then the function empties the set and takes in new contestants. From some of my simulations it seems like this function does not constantly allow only 10 threads at a specific time interval. Any suggestions on what I might be doing wrong. I tried to put as much info. as I can here. Let me know if there is anything you would like me to add.

Aucun commentaire:

Enregistrer un commentaire