Two threads using the same function

Basic question using theme theme.

I am modifying a program with two thread classes and now I would like to use a function defined in one class in both classes.

As a thread newbie (only playing with them for months), is it ok to move a function from the thread class to the main program and just call it from both classes, or do I need to duplicate the function into another class that doesn't have it?

Regards Simon

+3


source to share


2 answers


You can call the same function from both threads. The problem to be aware of is changing shared data from two threads at the same time. If a function tries to modify the same data from both threads, you end up with an unpredictable program.

So, the answer to your question is, "It depends on what the function does."



Of course it won't help to copy the function to both thread classes. What matters is what the function does, not the number of copies of code.

+9


source


blocking the thread may be required. threads running on 1 function / method can "block" this function in many languages ​​so that other threads cannot access it at the same time. http://en.wikipedia.org/wiki/Lock_(computer_science)



+2


source







All Articles