Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

CPU Bound Decorator in Wrapped Functions #42

Open
trin5tensa opened this issue Jun 25, 2021 · 1 comment
Open

CPU Bound Decorator in Wrapped Functions #42

trin5tensa opened this issue Jun 25, 2021 · 1 comment

Comments

@trin5tensa
Copy link

trin5tensa commented Jun 25, 2021

For context, I am a new user of unsync and I am exploring its use for the problem of running concurrent code triggered from a tkinter gui. I'm currently studying ways of getting data produced by concurrent operations back into tkinter's own event loop.
As part of that I've come across a problem with cpu bound functions.

In the following code the cpu_bound_2 function fails with this exception:


Traceback (most recent call last):
  File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/concurrent/futures/process.py", line 243, in _process_worker
    r = call_item.fn(*call_item.args, **call_item.kwargs)
  File "/Users/stephen/Documents/Coding/Scrapbook/env/lib/python3.9/site-packages/unsync/unsync.py", line 98, in _multiprocess_target
    return unsync.unsync_functions[func_name](*args, **kwargs)
KeyError: ('__main__', 'func')
"""

The above exception was the direct cause of the following exception:

KeyError: ('__main__', 'func')
import math
import sys
import time

from unsync import unsync


@unsync(cpu_bound=True)
def cpu_bound_1():
    for number in range(20_000_000):
        math.sqrt(number)
    print("Finishing cpu_bound_1")
    
    
def threadable():
    @unsync
    def func():
        time.sleep(3)
        print("Finishing threadable")
    return func


def cpu_bound_2():
    @unsync(cpu_bound=True)
    def func():
        for number in range(20_000_000):
            math.sqrt(number)
        print("Finishing cpu_bound_2")
    return func


def main():
    cpu_bound_1()
    threadable()()
    cpu_bound_2()()


if __name__ == '__main__':
    sys.exit(main())

Python 3.9 on macOS Big Sur 11.4.

@alex-sherman
Copy link
Owner

CPU bound functions are pickled by name, so they need to be defined in the global namespace. It's an annoying limitation, but not sure of a better way to do it.

I'll update the documentation to mention this.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants