将对象传递给另一个线程后无法访问某些成员变量
Can't access certain member variables after passing object to another thread
我有一个多线程应用程序,其中对象 A 具有链表 B 的实例。将 A 传递给另一个线程后,我无法访问 B。
定义 A:
struct Peer
{
public:
...
Linked_List *message_list;
...
Peer() {
...
message_list = new Linked_List;
...
};
...
};
定义 B:
class Linked_List {
public:
...
Linked_List();
int add(string);
string get();
string get_nb();
void clear(bool);
private:
struct Node* head;
HANDLE ghSemaphoreLinkedList;
HANDLE ghSemaphoreGet;
};
struct Node {
string data;
Node* next;
};
主线程:
Peer *client = new Peer;
CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE) &SendToPeer, &client, 0, &thread);
访问线程:
DWORD WINAPI SendToPeer(Peer *client)
{
while(1)
{
//While debugging, VSC++ says it can't read the memory of client->message_list
string msg = client->message_list->get();
}
}
可能是什么问题?
问候大卫
将 client
变量传递给 CreateThread()
的lpParameter
参数时,您需要删除 &
运算符:
//CreateThread(..., &client, ...);
CreateThread(..., client, ...);
SendToPeer()
期望接收Peer*
指针,但实际上您正在向其发送Peer**
指针。
我认为您可能只需要将指针值传递给函数,并且可能您应该尊重void*,因为CreateThread的第四个参数是LPVOID,它是void*。我没有测试它,希望它会起作用
DWORD WINAPI SendToPeer(LPVOID param)
{
Peer * client = (Peer*) param;
while(1)
{
//While debugging, VSC++ says it can't read the memory of client->message_list
string msg = client->message_list->get();
}
return 0;
}
Peer *client = new Peer;
CreateThread(NULL, 0, &SendToPeer, client, 0, &thread);
相关文章:
- 尝试通过多个向量访问变量时,向量下标超出范围
- 通过按地址访问变量
- 通过 get-Method 访问变量在类外不起作用
- 是否可以使用指针访问变量以避免直接编辑变量?
- 我无法访问变量的值,即使我通过范围传递了它
- 简单的问题 - 如何从单独的"结构"内的'class'访问变量?
- (C++) 从另一个类访问变量时值无效
- 返回实例变量的c++方法可以访问变量中的数据,但不能更改它,但在编译时不会生成错误
- 是否可以从字符串访问变量?
- 变量 z 无法从其他函数访问变量 x
- 如何在 C++ 中从 void 返回函数访问变量
- 在链接的程序集文件中,我想从 c++ 调用代码访问变量.是否可以在不触发访问冲突的情况下执行此操作?
- 在C 中本地声明隐藏的封闭范围(而非全局)中访问变量
- 从函数中删除动态内存分配,但无法访问变量
- 如何从派生类中的基类访问变量的值?
- 如何通过指针更快地访问变量,然后直接访问变量?
- 如何在公共类 c++ 中访问变量的值
- 从 Visual Studio 中的多个源文件访问变量
- 使用命名空间和模板类访问变量
- 从子对话框访问变量