samedi 27 janvier 2018

Pass by reference not working in std::thread constructor [duplicate]

This question already has an answer here:

I am trying to spawn a thread with a function that takes an object by reference, (string&) and modifies it. While the main thread waits for that thread to return. After the thread returns the main thread then applies some operation on the modified object.

Testing code as follows:-

/*It modifies the data and returns processed information by filtering the information*/
void process_data(string& data); 

int main(){
    /*it will get the parsed information from the source*/
    string parsed_data = get_parsed_data(source_id/*some source*/); 
    thread pre_process_thread(process_data, parsed_data);
    pre_process_thread.join();
    populate_obj(parsed_data);
    return 0;   
}

Now, my problem is that although the parsed_data is passed as a reference to process_data() and process data function is modifying that data as expected but somehow parsed_data, after the pre_process_thread has completed, is showing the original data. Ideally, when I am passing by reference it should show the modified value.

Aucun commentaire:

Enregistrer un commentaire