Skip to content

Instantly share code, notes, and snippets.

@Taiiwo
Created October 8, 2019 16:02
Show Gist options
  • Save Taiiwo/cb7ce8bea96ed82c23d5586ee0b08b1b to your computer and use it in GitHub Desktop.
Save Taiiwo/cb7ce8bea96ed82c23d5586ee0b08b1b to your computer and use it in GitHub Desktop.
Solving the halting problem in python
import asyncio
loop = asyncio.get_event_loop()
# returns true if coroutine function blocks or errors, else false
async def holds(function, arg):
# try block for catching errors
try:
# create a promise for the function to run in another thread
p = loop.run_in_executor(None, await function, (arg,))
# return if the coroutine takes more than 0.1 seconds to complete
# by awaiting the above promise for 0.1 seconds, and returning true if
# it didn't finish in time
return await asyncio.wait([p], timeout=0.1)[1]
except:
# code errored, so return true
return True
async def weird(f):
if await holds(f, f):
while True:
pass
else:
return
async def main():
# the beginning of the event loop
print(await holds(weird, weird))
if __name__ == "__main__":
# put main() in the event loop, then wait until it's done
loop.run_until_complete(main())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment