Ajay Alex
Ajay Alex

Reputation: 21

Run another function only when the previous function is finished in python

I have 4 functions:

  1. firstfunc()
  2. secondfunc()
  3. thirdfunc()
  4. forthfunc()

I want to run these functions sequentially(order doesn't matter) and not together, I need the functions to wait till one of them completes the task, and then another one should start executing.

Each function returns a different value which is then to be stored in a variable and later used for further data processing. How can this be done in python? I am kinda a novice in python.

Upvotes: 0

Views: 1355

Answers (2)

Eli Borodach
Eli Borodach

Reputation: 597

I guess your question is from leetcode, there was there a questions with 3 functions, here is my solution:

from threading import Lock


class Foo:
    def __init__(self):
        self.lock_first = Lock()
        self.lock_first.acquire()
        self.lock_second = Lock()
        self.lock_second.acquire()

    def first(self, printFirst: 'Callable[[], None]') -> None:
        # printFirst() outputs "first". Do not change or remove this line.
        printFirst()
        self.lock_first.release()


    def second(self, printSecond: 'Callable[[], None]') -> None:
        while self.lock_first.locked():
            continue
            
        # printSecond() outputs "second". Do not change or remove this line.
        printSecond()
        self.lock_second.release()


    def third(self, printThird: 'Callable[[], None]') -> None:
        
        while self.lock_first.locked() or self.lock_second.locked():
            continue
        
        # printThird() outputs "third". Do not change or remove this line.
        printThird()

You can also look in a very similar solution over here (in case you have a subscription): https://leetcode.com/problems/print-in-order/editorial/

Upvotes: 0

samkayz
samkayz

Reputation: 97

Programming language execute from top unless stated otherwise by the use of conditional statements. What you want to achieve here is pretty the way you arrange it.

Execute the first one followed by the second and so on.

Upvotes: 1

Related Questions