что-то странное с потоками posix в C ++ - PullRequest
0 голосов
/ 24 декабря 2011

Я сталкиваюсь со странной ошибкой с pthreads в C ++, пытаюсь запустить этот код:

typedef struct
{
    struct sockaddr_in clienAddr;
    int clientLength;
    string message;
}param;

pthread_t clientThread;

param sentParam ;
sentParam.clienAddr = clientAddress;
sentParam.clientLength= client_info;
sentParam.message=buffString;

cout <<"sentParam: "<<sentParam.message<<endl;
// it prints well.

int i = pthread_create(&clientThread, NULL, handleClientRequestRead,&sentParam );
cout <<"i: "<<i<<endl;
the function which be called

void* handleClientRequestRead(void* params)
{
    // cout<<"params: "<< ;
    string msg = (( param *)(params))->message;
}

Когда я пытаюсь напечатать msg, он пустЛюбая помощь будет оценена

Ответы [ 2 ]

6 голосов
/ 24 декабря 2011

Я предполагаю, что когда handleClientRequestRead вызывается, sentParam уже вышел из области видимости и его память была повторно использована для других целей.

Вы должны выделить память для ваших параметров в месте,остается действительным, когда вы получите доступ к нему из потока (например, в куче, помня, что вы должны освободить его, когда он вам больше не нужен; действительная помощь может быть shared_ptr).

Кстати, в C ++ вам не нужен трюк typedef для struct s.

1 голос
/ 24 декабря 2011

Я согласен с @Matteo выше:

struct param
{
    struct sockaddr_in clienAddr;
    int clientLength;
    string message;
};


 void someFunction()
 {
    static int   sentCount = 0;
    static param sentParam[10];
//  ^^^^^^ Notice these are static
//         Thus they will last the length of the program.
//         An alternative is to dynamically creation but then you have
//         to destroy them at some point.
//


    if (count >= 10)
    {    throw std::runtime_error("Too many threads");
    }
//         If you want to keep more than 10 or use a dynamic number 
//         then use a std::list, NOT a std::vector

    sentParam[sentCount].clienAddr = clientAddress;
    sentParam[sentCount].clientLength= client_info;
    sentParam[sentCount].message=buffString;

    cout <<"sentParam: "<<sentParam.message<<endl;
    // it prints well.


    pthread_t clientThread;
    int i = pthread_create(&clientThread, NULL, handleClientRequestRead,&sentParam[sentCount] );
    cout <<"i: "<<i<<endl;

    if (i == 0)
    {
        ++sentCount;
    }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...