将对象传递给另一个线程后无法访问某些成员变量

时间:2014-01-15 01:37:57

标签: c++ multithreading

我有一个多线程应用程序,其中对象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();
    }
}

可能是什么问题?

此致 大卫

2 个答案:

答案 0 :(得分:3)

&变量传递给client的{​​{1}}参数时,您需要删除lpParameter运算符:

CreateThread()

//CreateThread(..., &client, ...); CreateThread(..., client, ...); 期望收到SendToPeer()指针,但实际上您正在发送Peer*指针。

答案 1 :(得分:0)

我认为你可能只需要将指针值传递给函数,也许你应该尊重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);