Home > Blockchain >  Update index variables in threads
Update index variables in threads

Time:11-18

I have objects like balls. These objects are dynamically created and stacked into a vector. For each of these balls, a separate stream is created that updates its coordinates. Each of these streams has a reference to a vector with balls and knows the sequence number of its ball. Then, let's say I need to delete several balls and streams associated with them.

I did it like this: the sword has a bool killMe variable that becomes true when the ball needs to be removed. The thread that updates the coordinates notices that the ball needs to be removed, removes the ball, and terminates on its own. But when the ball is removed from the vector, the sequence numbers of the subsequent balls change and their streams, trying to refer to them the next time, cause the program to crash.

How to organize a timely update of the ball index in their streams?

CodePudding user response:

Rather than each thread having an index into the vector, why not pass a reference to the object being worked on?

Note that this may still be problematic if your vector is vector<Ball>, as I'm not sure what happens to references to objects that are moved. That sounds like a problem.

But you could store vector<std::shared_ptr<Ball>> and then you're golden.

Another choice if you really want to use indexes is still to use a vector of shared pointers but then you can nullify the pointers you need to delete -- leaving holes in your vector, but at least you aren't moving things around.

The other choice involves mutexes, and you'll be mutex-locked A LOT. This seems less useful.

  • Related