![]() Operating systems capable of multithreading offer functions to synchronize threads. This is by far not all which a serious programmer has to take care of when having multiple threads dealing with the same memory because you cannot know when exactly the scheduler of the underlying operating system will decide to context switch between the threads. So you would write a "volatile" type modifier before the type ("int" in your example). This can happen even is you access this variable only in one line of code (because the compiler may decide to put the variable to a CPU register and write it back later).īugs of this kind are hard to track and thus it´s good practice to declare such variables as "volatile" - this tells the compiler to always work on memory directly instead of using a CPU register. Another thread starts reading just after the first one and writes back after it and overwrites the result of the first calculation. Is´s a general problem of mutithreaded programming to be aware of race conditions:Ĭonsider the case of one thread "delete"ing an object at a pointer and another thread working with this very pointer at the same time.Īnother example is one thread reads from a shared variable makes some computations and writes back the new value. Of course you can use a global structure, global variables or static fields to make both threads able to know the same object or variable. ![]() If two threads know one and the same object of the class "test" (your example) "i" can be written to from both of them - but only inside member methods of class test (because it is declared private). ![]() Basically threads are not a language feature of C++ and therefore it has nothing to do with multithreading if you are in the right scope to access a member variable. ![]()
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |