简体   繁体   中英

something strange with posix threads in C++

I face a strange error with pthreads in C++, I try to run this code:

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;
}

When I try to print msg it's empty. Any help will be appreciated

My guess is that when handleClientRequestRead gets called sentParam has already gone out of scope and its memory has been reused for other purposes.

You should allocate memory for your parameters in a location that will still be valid when you'll access it from the thread (eg on the heap, keeping in mind that you must free it when you don't need it anymore; a valid help can be shared_ptr ).

By the way, in C++ you don't need the typedef trick for struct s.

I agree with @Matteo above:

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;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM