'Check for condition during blocking call

I am writing some python code to work with the Ethereum blockchain. After I send a transaction, I run a blocking call that waits for the transaction receipt to be verified. While my program is waiting to receive the receipt I want to simultaneously check for a condition that would ultimately cancel the blocking call. I've been looking into using async functions or asyncio but solutions I've seen don't seem to work in my case.

For more context, I have thread 1 which first builds the transaction and then makes a blocking call to wait for the receipt from said transaction:

def thread_1_func(pending_txns: dict, task_name):
  # Building transaction here and storing transaction hash in 'txn_hash'
  web3.eth.wait_for_transaction_receipt(txn_hash) # blocking call
  if pending_txns[task_name] == "Modified": # want to check this simultaneously with the blocking call
    sys.exit() # close the thread since the receipt will now never actually be received

I then have a second thread that only runs if the user modifies a certain file. The file modification indicates that we need to send a different transaction to modify that original sent transaction before it is verified and a receipt is received:

def thread_2_func(pending_txns: dict, task_name):
  # build modified version of transaction and send it, store new transaction hash in 'txn_hash'
  pending_txns[task_name] = "Modified" #This will validate the condition for the other thread to stop
  web3.eth.wait_for_transaction_receipt(txn_hash) #now this thread can block and wait for receipt

Also important to note, 'pending_txns' is a dictionary I currently use to share info about pending transactions amongst threads. I recognize that this certainly may not be threadsafe, but it has worked thus far for what I need.

I want to be able to continuously check the 'pending_txns' dict for an updated value so that I can stop thread 1. What would be the best way to achieve this?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source