理解在c++中的类中创建线程时遇到问题
Trouble understanding creating threads within a class in c++
新手问题。。。我创建了这个类:
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键控的线程。
相关文章:
- 从不同线程使用int64的不同字节安全吗
- 删除一个线程上有数百万个字符串的大型哈希映射会影响另一个线程的性能
- 在C++中使用cURL和多线程
- 为什么我的C#代码在调用回C++COM直到Task时会暂停.等待/线程.加入
- 在cuda线程之间共享大量常量数据
- 如何将元素添加到数组的线程安全函数?
- 线程,如果else语句,都是错误的上下文切换后,会发生什么
- C++Boost Asio Pool线程,带有lambda函数和传递引用变量
- Qt C++静态thread_local QNetworkAccessManager是线程应用程序的好选择吗
- 异常属于C++中的线程还是进程
- C++中的线程安全删除
- C++使用params创建线程函数会导致转换错误
- 类与私有变量的其他类之间的线程安全性
- CoInitialize()在单独的线程上崩溃而不返回
- C++线程安全:如果只有一个线程可以写入非原子变量,但多个线程从中读取. 会遇到问题吗?
- 可中断线程类 C++11 - 遇到错误?
- 我遇到了一个关于多线程的小问题.需要多线程来计算 Pi 和方差
- 当一个线程遇到异常时,是否可以冻结所有线程
- 理解在c++中的类中创建线程时遇到问题
- 语义问题 "Attempt to use a deleted function" 遇到使用 std::线程用法编译 c++ 代码