ryan9025
ryan9025

Reputation: 269

Threading two functions inside a method of a class Python

I want to run 2 functions inside a method of a class at the same time in Python. I tried to use threading module but it doesn't work. My example codes are as below:

import os, sys
import threading
from threading import Thread

class Example():
    def __init__(self):
        self.method_1()

    def method_1(self):

        def run(self):
            threading.Thread(target = function_a(self)).start()
            threading.Thread(target = function_b(self)).start()

        def function_a(self):
            for i in range(10):
                print (1)

        def function_b(self):
            for i in range(10):
                print (2)

        run(self)


Example()

If above codes get executed, it will just print all 1s first and then all 2s. However, what I want is to print 1 and 2 at the same time. Thus, the desired output should be them mixed up.

Is threading module capable to do that? If not, what module can do that? If anyone knows how to solve it, please let me know. Appreciated!!

Upvotes: 1

Views: 9172

Answers (2)

Hannu
Hannu

Reputation: 12205

You need to pass the argument differently. Now you are actually executing your function in the threading.Thread initialisation call instead of creating a thread that executes the function.

If something needs a function as a parameter, always use just function. If you write function(), Python will not pass the actual function as a parameter, but executes the function on the spot and uses the return value instead.

def run(self):
    threading.Thread(target = function_a, args=(self,)).start()
    threading.Thread(target = function_b, args=(self,)).start()

Upvotes: 5

Vasilis G.
Vasilis G.

Reputation: 7844

Here it is:

import os, sys
import threading
from threading import Thread
import time

class Example():
    def __init__(self):
        self.method_1()

    def method_1(self):

        def run(self):
            threading.Thread(target = function_a, args = (self,)).start()
            threading.Thread(target = function_b, args = (self,)).start()

        def function_a(self):
            for i in range(10):
                print (1)
                time.sleep(0.01) # Add some delay here

        def function_b(self):
            for i in range(10):
                print (2)
                time.sleep(0.01) # and here


        run(self)


Example()

You will get outputs like this:

1
2
1
2
2
1
2
1
2
1
2
1
2
1
2
1
2
1
2
1

Upvotes: 0

Related Questions