0

I am working with multi-threading. There is a thread that periodically adds to a certain variable, say every 5 seconds. I want to make it so that, given a call to function f(), additions to that variable will have no effect.

I can't find how to do this anywhere and I'm not sure where to start. Is there any syntax that makes certain operations not no effect no specific variables for a certain duration?

Or is there any starting point someone could give me and I can figure out the rest?

Thanks.

Shoogiebaba
  • 81
  • 10
  • Could you use another variable as a multiplier for the addition, and when no additions should be done, simply set the multiplier to 0? – Schlaus Oct 02 '15 at 07:48
  • This is not a good idea. If a treatment of one variable is complicated, use special methods and flags for it (as metareven proposes). But, don't change the basic meaning of operators (and especially not temporarily) - it will bring more harm than gain even if you finally succeed. – honza_p Oct 02 '15 at 08:03
  • Yeah, this works! Pretty similar to Metareven. – Shoogiebaba Oct 02 '15 at 08:06

2 Answers2

2

I would suggest creating an addToVariable or setVariable method to take care of the actual adding to the variable in question. This way you can just set a flag, and if the flag is set addToVariable returns immediately instead of actually adding to the variable in question.

If not, you should look into operator overloading. Basically what you want is to make your own number-class and write a new add function which contains some sort of flag that stops further additions to have any effect.

Metareven
  • 822
  • 2
  • 7
  • 26
  • Your first suggestion should work, thanks! The second suggestion should work as well, but the first should suffice. – Shoogiebaba Oct 02 '15 at 08:04
1

You could protect the increment with a lock and acquire the lock for the duration of f() call:

import threading
import time

lock = threading.Lock()
# ...
def f():
    with lock:
        # the rest of the function

# incrementing thread
while True:
    time.sleep(5 - timer() % 5) # increment on 5 second boundaries
    with lock:
        x += 1

The incrementing thread is blocked while f() is executed. See also, How to run a function periodically in python

Community
  • 1
  • 1
jfs
  • 399,953
  • 195
  • 994
  • 1,670