Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Two threads using same function

Basic using threads question here.

I'm modifying a program with 2 thread classes and I'd like to use a function defined in one class in both classes now.

As a thread newbie (only been playing with them for a few months) is it OK to move the function out of the thread class into the main program and just call it from both classes or do I need to duplicate the function in the other class that doesn't have it?

regards Simon

like image 402
SimpleSi Avatar asked Feb 26 '26 21:02

SimpleSi


1 Answers

You can call the same function from both threads. The issue to be aware of is modifying shared data from two threads at once. If the function attempts to modify the same data from both threads, you will end up with an unpredictable program.

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

It certainly won't help to copy the function into both thread classes. What matters is what the function does, not how many copies of the code there are.

like image 51
Ned Batchelder Avatar answered Mar 01 '26 10:03

Ned Batchelder



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!