JeffR
JeffR

Reputation: 805

Trouble understanding creating threads within a class in c++

Newbie question...I created this class:

class CThreadMaster
{
public:
    CThreadMaster();
    ~CThreadMaster();

    void AddGroup(TCHAR *sGroupName);   // Adds a group to the class
    void RemoveGroup(TCHAR *sGroupName);    // Removes a group from the class
    void CleanupGroups(void);  // somehow go through the list of created classes (?)

private:
    TCHAR *m_GroupName;
    HANDLE *m_GroupThreadHandle;

};

The group names are in a database file. My goal is to create a thread for any new groups appearing in the file. I thought I could use a class to keep track of the group name and associated thread handle.

I have an array to do this in the code below, but this seems horribly inefficient, and that's why I want to use a class - maybe a class array? How do I cycle through all instances of created classes so I can keep track of groups that have an associated thread already created?

// In main(); each thread has a group name and a handle
#define GROUPSMAX 1024  // arbitrary number; would prefer not to be limited
struct THREADMASTER
{
HANDLE hGroupThreadHandle;
TCHAR sGroupName[128];
};
static struct THREADMASTER aGroupThreads[500] = {0,0};

// Get the group names from the database (...)

// See if we are already monitoring the group name.
for (i=0;i<GROUPSMAX;i++)
    {
    // See if the array has a group name filled in.
    if (_tcslen(aGroupThreads[i].sGroupName))
        {
        // Get the currently saved group name
        _stprintf_s(sGroupNameToFind,dwSizeAllGroups ,L"%s",aGroupThreads[i].sGroupName);

        // If the group name is found, exit this for loop.
        if (strstr(sAllGroupsInDB,sGroupNameToFind))
            {
            bFound = TRUE;
            break;
            }
        }
    }

if (bFound == FALSE)
    {
    for (i=0;i<GROUPSMAX;i++)
        {
        // See if the array has a group name filled in.
        if (_tcslen(aGroupThreads[i].sGroupName) == 0)
            {
            // create the thread and assign the handle
            aGroupThreads[i].sGroupName = sGroupNameToFind...
            aGroupThreads[i].hGroupThreadHandle = _beginthreadex(...)
            break;
            }
        }
    }

If I create a thread, I can get the thread handle and then check if the thread is running by trying to open the thread handle.

Any suggestions?

Upvotes: 0

Views: 93

Answers (1)

Moo-Juice
Moo-Juice

Reputation: 38825

You're making more work for yourself. Try look at std::map, for example... Using a map you can associate threads keyed by their thread ID.

Upvotes: 1

Related Questions