I'm working on a multithreaded project using the boost::thread library, and I've hit a snag. I set up the threads with a few variables passed through the constructors. With the variables I'm looking to modify, I referenced them using boost::ref(variable) instead of a direct pass to the function.
The problem is that even with these variables referenced instead of copied, when I modify them in the thread function, the original variable isn't modified like it would be in a normal function. Each thread ends up retaining its own private copy of the variable, and never modifies the original.
The threads work, but since they aren't modifying the original variable, they're all somewhat off doing their own thing, no coordination between them. I've looked into mutexes, but the boost documentation is about as clear and concise as a pool of pudding. I don't think they apply in this circumstance anyway.
Is there anyone with experience in this area that can help? I'd greatly appreciate it.
NOTE: My code is becoming increasingly long and complex, and I thought it would be more helpful to simply describe what I'm trying to accomplish as best I can, rather than post 250+ lines of code. If you think seeing my code would help, let me know and I'll post it.
Hi Gen,
I'll definitely agree that the boost threading library documentation is about as useful as a wet paper bag.
As for your problem, you have a couple of ways to do this.
1) Make the variable static, and put locks around it to prevent concurrent modification and ensure thread safety.
2) Make another class that's a singleton that stores the variable for you. Then use encapsulated methods with locking.
The general idea of what your trying to do is bad practice. Your trying to pass a variable by reference to multiple threads. By passing this variable by reference you are unable to safely maintain locks around it to ensure it's not read/modified concurrently and causing undefined behavior.