Beispiel #1
0
    def test_contexts(self):
        def test_with_kernel():
            self.assertIsNotNone(kernels.get_kernel())

        self.assertIsNone(kernels.get_kernel())
        kernels.call_with_kernel(test_with_kernel)
        self.assertIsNone(kernels.get_kernel())
Beispiel #2
0
from g1.asyncs import kernels
from g1.asyncs.bases import signals
from g1.asyncs.bases import timers


async def handle_signals(duration):
    print('pid: %d' % os.getpid())
    timers.timeout_after(duration)
    with signals.SignalSource() as source:
        signums = [signal.SIGINT, signal.SIGTERM]
        print('handle signals for %.3f seconds: %r' % (duration, signums))
        for signum in signums:
            source.enable(signum)
        try:
            while True:
                print('receive signal: %r' % await source.get())
        except timers.Timeout:
            print('timeout')


def main(argv):
    if len(argv) < 2:
        print('usage: %s duration' % argv[0], file=sys.stderr)
        return 1
    kernels.run(handle_signals(float(argv[1])))
    return 0


if __name__ == '__main__':
    sys.exit(kernels.call_with_kernel(main, sys.argv))
Beispiel #3
0
async def compute(x):
    duration = random.uniform(0, 4)
    print('spend %.3f seconds computing' % duration)
    await timers.sleep(duration)
    return x * x


async def accumulate(ts):
    total = 0
    for task in ts:
        total += await task.get_result()
    return total


def main(_):
    start = time.perf_counter()
    ts = [tasks.spawn(compute(i + 1)) for i in range(10)]
    total = kernels.run(accumulate(ts))
    elapsed = time.perf_counter() - start
    print('result: %d' % total)
    print('total elapsed time: %.3f seconds' % elapsed)
    return 0


if __name__ == '__main__':
    print('before call_with_kernel: kernel=%s' % kernels.get_kernel())
    status = kernels.call_with_kernel(main, sys.argv)
    print('after call_with_kernel: kernel=%s' % kernels.get_kernel())
    sys.exit(status)