pthread, mutex, functions, classes...
| theChameleon (12) | |||
| hello how do i make both threads have access to the same set of updated data, when they call different functions? in addition, is the way i pass in the variable "myObjs" correct? can i pass in STL containers the same way? example:
in this code, thread1 will increase the value of member variables, while thread2 will decrease the value of the member variables... but i need them to be updated. in addition, when im adding the values, how do i mutex lock the minus function, so it wont add and minus at the same time, and vice versa? if i change the code to use STL container, i would edit the function "plus()" to add a new object, and the function "minus()" to erase an object. lastly, how do i use the functions in queue, and the class? it generates an error when it's in the thread function. the error is: error: request for member 'size' in 'myObjs', which is non class type 'std::queue<aClass, std:: deque<aClass, std::allocator <aClass>>>*' | |||
| theChameleon (12) | |||
| the error has been resolved. so, can somebody help me regarding the things i mentioned in the original post? | |||
| Zaita (1607) | |||||
http://en.wikipedia.org/wiki/Singleton_pattern
See above.
When using a class, the mutex becomes a member and can then be used to lock down various sections of code, including methods (minus and plus) that belong to that class. You can also declare a global mutex if your not going to use OO.
The way you have tried to do this is a very bad idea. Creating a function local variable and passing it as a reference to the threads. I will make a few suggestions. 1. Have a look at OO, and how to implement a Singleton-Class. 2. Look at a thread library like Boost that provides easy access to mutexes, barriers and thread creation/management. 3. Don't pass the address of your container through to the thread. Either make it a global variable, or part of a class (ideally a singleton, so you can lock the code when required). | |||||
| Zaita (1607) | |||
| How new are you to C++? Multi-Threaded development is exponentially more difficult that single-threaded development. There are alot of concepts that you have to learn, and you basically have to re-think the design of large parts of your application if you go down the multi-threaded path. Also, I would have a look at Thread-Specific Storage too. This allows you to have static variables, singleton classes that are 1 per thread, as opposed to 1 per application. | |||
This topic is archived - New replies not allowed.
