How to write my following C code using setjmp/longjmp in Python?

1k views Asked by At

I was wondering if the implementation of setjmp/longjmp is possible in Python? If not, is there any equivalent alternative?

#include <setjmp.h>
#include <stdio.h>
jmp_buf env;
void fl(void);
void f2(void);
int main(void)
{
  if (setjmp(env) == 0)
    printf("setjmp returned 0\n");
  else {
    printf("Program terminates: longjmp called\n");
    return 0;
  }
  f1();
  printf("Pregram terminates normally\n");
  return O;
}
void f1(void)
{
  printf("f1 begins\n");
  f2();
  printf("f1 returns\n");
}
void f2(void)
{
  printf("f2 begins\n");
  longjmp(env, 1);
  printf("f2 returns\n");
}
1

There are 1 answers

0
DenisKolodin On

Python demands another approaches because direct use of longjmp isn't safe for Python's stack. Use greenlet:

from greenlet import greenlet

def test1():
    print 12
    gr2.switch()
    print 34

def test2():
    print 56
    gr1.switch()
    print 78

gr1 = greenlet(test1)
gr2 = greenlet(test2)
gr1.switch()