理解在c++中的类中创建线程时遇到问题

Trouble understanding creating threads within a class in c++

本文关键字:线程 遇到 问题 创建 c++      更新时间:2023-10-16

新手问题。。。我创建了这个类:

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;
};

组名在数据库文件中。我的目标是为文件中出现的任何新组创建一个线程。我想我可以使用一个类来跟踪组名称和相关的线程句柄。

在下面的代码中,我有一个数组来实现这一点,但这似乎效率非常低,这就是为什么我想使用类——也许是类数组?如何循环浏览已创建类的所有实例,以便跟踪已创建关联线程的组?

// 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};

//从数据库中获取组名称(…)

// 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;
            }
        }
    }

如果我创建了一个线程,我可以获得线程句柄,然后通过尝试打开线程句柄来检查线程是否正在运行。

有什么建议吗?

你正在为自己做更多的工作。试着看看std::map,例如。。。使用映射,您可以关联由线程ID键控的线程。