1

This is the first time I am using the multithreading in python. I found many documents in related to multithread and multi-processing in python 2.7.9 and researched also multi-threading link. But I didn't get clue how to implement my application. I am having application based on self.count, which is in the below code is 5. I have to create a 5 threads or process and when I call d.sum(1,2) This should call sum function in 5 different thread and execute in parallel and update the result in result dictionary with thread-name and result.

Now my current approach is happening serially. But I want to make this as parallel using thread or process. Please help in achieving this.

Thanks in advance. The code snippets are highly appreciated.

I have the code so far.

class Base(object):

    def __init__(self): 
        self.count =5  # Count = 5 is used to create a 
                       #number of thread or process to run parallel

    def sum(self, a, b):
        result = {}
        for i in range(0,self.count):
            result[i] = a + b

        return result

    def diff(self, a, b):
        result = {}
        for i in range(0,self.count):
            result[i] = a - b

        return result

    def mull(self, a, b):
        result = {}
        for i in range(0,self.count):
            result[i] = a * b

        return result

    def division(self, a, b):
        result = {}
        for i in range(0,self.count):
            result[i] = a / b
        return result

d = Base() 
print d.sum(1,2)
print d.diff(2,1)
Community
  • 1
  • 1

1 Answers1

1

Because of the GIL if you use threads, they won't run in parallel. You need to use multiprocessing, and the multiprocessing Queue module to communicate between the processes.

One of the best places for info on modules like this is pymotw (python module of the week).

The communication section of the multiprocessing section shows a full example.

https://pymotw.com/2/multiprocessing/communication.html

Stuart Axon
  • 1,844
  • 1
  • 26
  • 44
  • Thanks alot Stuart Axon. Could you please provide any links or documents related to my application. –  Nov 28 '15 at 11:10
  • @Sana, look to the right of the StackOverflow interface for lots of related questions (and answers). In particular, [this one](https://stackoverflow.com/questions/3044580/multiprocessing-vs-threading-python?rq=1) was highlighted on my side. – Oliver W. Nov 28 '15 at 11:16
  • Thank you @Oliver W, Could you please provide example code snippets or some coding guidelines to build my application –  Nov 28 '15 at 13:16
  • StuartAxon you should add the link to that related question into your answer (answers are more permanent than comments and it would help direct future readers) – LinkBerest Nov 29 '15 at 15:44
  • Yup, typed 1st answer on a tablet so was a bit sparse. – Stuart Axon Nov 30 '15 at 10:37