Hello All,

I needed some clarifications w.r.t making functions thread safe. Now, i understand that irregularities can occur in results when not making functions thread safe. But could this somehow lead to a crash? (say some illegal access of memory)

Could anyone please give an example of this(something that you have come across)?

Thanks!

I needed some clarifications w.r.t making functions thread safe.

Can you be more specific?

But could this somehow lead to a crash? (say some illegal access of memory)

Sure it can. For example, what if, in the middle of a loop that iterates, with iterators, through the elements of a vector, another thread resizes the vector, effectively changing the memory location of the elements and invalidating any existing iterators. That's a simple example, but that basic logic carries over to many many more examples, some much less obvious than this one. Then, there are some more subtle problems that might not lead to a crash but might result in corrupt results, like non-atomic reads of variables or objects that might give corrupt values leading to corrupt results.

I needed some clarifications w.r.t making functions thread safe.

I prefer to think of it as making data accesses thread-safe. Any data that is shared between multiple threads (either as some shared "singleton" data, or inter-thread communications) should be protected in some way to avoid concurrent uses of that data in ways that could lead to trouble, as in my examples above. Usually, this implies making the access to the data possible only through some specific channels (e.g., member-functions), and then including some mutual exclusion mechanism within those functions.

It would help if you gave more details as to what you are really trying to accomplish.

For example, what if, in the middle of a loop that iterates, with iterators, through the elements of a vector, another thread resizes the vector, effectively changing the memory location of the elements and invalidating any existing iterators.

Thanks a lot for the response mike_2000_17! That was pretty much what i wanted to know.

@mike_2000_17, deceptikon

Well, i have this library implementation of an R-Tree and i needed to make sure that it was completely thread safe. I guess the only option is to read through each function in it, then check if any data could simultaneously be accessed by multiple threads(like some global data).

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.