freaka61
freaka61

Reputation: 35

Multiple arguments (with struct) error using pthread

I'm working on a multiclient chat project.

Here is my code:

struct RecvDataModel
{
    int sockAddr;
    char *inData;
};

void *ProcessData(void *arg);

void Client::Recv(int sockAddr, char *inData)
{
    RecvDataModel outData;
    outData.sockAddr = sockAddr;
    outData.inData = inData;
    pthread_t rThr;
    pthread_create(&rThr, NULL, ProcessData, (void*)&outData);
}

void *ProcessData(void *arg)
{
    RecvDataModel *inData = (RecvDataModel*)arg;
    cout << inData->inData << endl;
    return 0;
}

Basically if sockAddr (in Client::Recv) equals "55" ProcessData's cout function writing "31784736", if equals "0" cout's "5120"

That's my big problem! I can't continue without this! (I'm using eclipse C++) What's the problem? I have already looked some example projects like this: Link >>>

Upvotes: 2

Views: 2035

Answers (2)

James M
James M

Reputation: 16728

You're passing a pointer to a RecvDataModel which is a function-local variable. It will go out of scope at the end of the Client::Recv function.

Try allocating it with new instead:

RecvDataModel * outData = new RecvDataModel();
outData->sockAddr = sockAddr;
outData->inData = inData;
pthread_t rThr;
pthread_create(&rThr, NULL, ProcessData, outData);

Upvotes: 3

Carl Norum
Carl Norum

Reputation: 225162

Don't pass around pointers to local variables that go out of scope. As soon as you create that thread, outData isn't valid anymore, and so the pointer you gave to it is no good. You need to declare outData with a static qualifier, or allocate space for it dynamically so that it doesn't vanish when Client::Recv returns.

Upvotes: 2

Related Questions