0

Within the __init__ of my class I want to trigger a thread that handles a function. For some reason the thread isnt triggered though, nothing just happens:

class OrderBook:

    # Create two sorted lists for bids and asks
    def __init__(self, bids=None, asks=None):
        if asks is None:
            asks = []
        if bids is None:
            bids = []
        self.bids = sortedcontainers.SortedList(bids, key=lambda order: -order.price)
        self.asks = sortedcontainers.SortedList(asks, key=lambda order: order.price)

        # Populate Orderbook with 50 orders
        threading.Thread(target=populate_orderbook(self, 10)).start()
        print(f'Orderbook initialized..')

    ...

And the function to be triggered which isnt though

def populate_orderbook(orderbook_instance, n):
    order_type = ['Limit']
    side = ['Buy', 'Sell']

    i = 1
    while i < n:
        # Create random order
        order_obj = Order(
            order_type=order_type[0],
            side=random.choice(side),
            price=random.randint(1, 1000),
            power=random.randint(1, 1000),
        )
        orderbook_instance.add(order_obj)
    print(f'Orderbook prepopulated..')
JSRB
  • 2,492
  • 1
  • 17
  • 48

1 Answers1

1

You are calling the target function eagerly, on the main thread.

You have to pass the function as an argument to the Thread constructor, and the arguments in separate, so that the function will be called inside the running thread:

        threading.Thread(target=populate_orderbook, args=(self, 10)).start()
jsbueno
  • 99,910
  • 10
  • 151
  • 209