multithreading - C++ return value from multithreads using reference -


here code:

vector<myclass> objs; objs.resize(4);  vector<thread> multi_threads; multi_threads.resize(4);  for(int = 0; < 4; i++) {     multi_threads[i] = std::thread(&myfunction, &objs[i]);                      // each thread change member variable in objs[i]     multi_threads[i].join(); } 

i expect elements in objs can changed @ each thread. after threads finished, can access member data.

however, when program finished above loop, member variables i'd not changed @ all.

i guess because multi-threading mechanism in c++, don't know did wrong. , may know how achieve expectation?

many thanks.

================================================================================= edit:

here source code of myfunc:

void myfunc(myclass &obj) {     vector<thread> myf_threads;     myf_threads.resize(10);     for(int = 0; < 10; i++)     {         myf_threads[i] = std::thread(&anotherclass::increasedata, &obj);         myf_threads[i].join();     }  } 

and here anotherclass::increasedata:

void anotherclass::increasedata(myclass& obj) {     obj.add(); }  void myclass::add() {     data++; } 

objs empty when first accessed, causing undefined behaviour:

multi_threads[i] = std::thread(&myfunction, &objs[i]);                                            //^^ 'objs' empty, access                                            // out-of-bounds. 

there must instances of myclass within objs before accessing it. avoid potential reallocation of internal buffer used objs vector allocating required number of elements upfront. if reallocation occurs previous pointers acquired dangling:

std::vector<myclass> objs(4); std::vector<std::thread> multi_threads(objs.size()); 

to avoid sequential execution of threads join() threads in subsequent loop instead of in creation loop:

for(int = 0; < 4; i++) {     multi_threads[i] = std::thread(&myfunction, &objs[i]); }  (auto& t: multi_threads) t.join(); 

see demo.


after update, appears function being used thread taking reference, not pointer, myclass instance (even though pointer being passed std::thread constructor?). in case, std::ref(objs[i]) must used avoid copying of myclass instance std::thread constructor (see demo). note std::thread::thread() reference page:

the arguments thread function copied value. if reference argument needs passed thread function, has wrapped (e.g. std::ref or std::cref).


Comments

Popular posts from this blog

ios - UICollectionView Self Sizing Cells with Auto Layout -

node.js - ldapjs - write after end error -

DOM Manipulation in Wordpress (and elsewhere) using php -