Noor
Noor

Reputation: 20150

Python threading proper way

I am new to Python Threading, Threading as well, and I have never used it. That's how I am using it.

I have a class Source and I want that its method evaluate is executed in a thread. The evaluate method call a Utility function increment defined outside the class which increments a global variable. Incrementing the global variable should be performed in a critical section. Also, after some processing, I need to pause the thread for some seconds. That's how I implement it:

import threading
caseGT = threading.Lock()
GT = 0
def increment():
    with caseGT:
        GT = GT + 1

class Source:
    def evaluate(self):
        for (someCondition):
            ...
            ...
            increment()
            ...
            ...
            time.sleep(2)

That's how I am calling the method evaluate:

s = Source(....)
Thread(s.evaluate()).start()

I am getting valid result with testdata. But my questions are:

  1. I am wondering whether it is going to work properly when many threads are doing to work at the same time ?

  2. Also, is there a better way to write use threading in this situation ?

Upvotes: 0

Views: 89

Answers (1)

Grr
Grr

Reputation: 16079

The way I like to use threading is to use an iterable to launch threads.

workers = []
for item in some_list:
    worker = Thread(target=some_func, args=(item,))
    workers.append(worker)
    worker.start()
for worker in workers:
    worker.join()

So I imagine that in your context you would want to define a method within Source that lets you pass an iterable and then start threads using items from that iterable as arguments. In your context with just one argument going to the evaluate method your implementation is fine. But I think scaling to multiple threads for the same method could be a problem with that usage.

Upvotes: 1

Related Questions