multi_vm_isolate.c 1.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. #include "pocketpy.h"
  2. #include "threads.h"
  3. #include <stdio.h>
  4. int run_huge_job_in_vm1(void* arg) {
  5. py_switchvm(1);
  6. bool ok = py_exec((const char*)arg, "<job>", EXEC_MODE, NULL);
  7. if(!ok) {
  8. py_printexc();
  9. return 1;
  10. }
  11. return 0;
  12. }
  13. int main() {
  14. py_initialize();
  15. bool ok = py_exec("print('Hello world from VM0!')", "<string1>", EXEC_MODE, NULL);
  16. if(!ok) {
  17. py_printexc();
  18. return 1;
  19. }
  20. printf("main vm index: %d\n", py_currentvm());
  21. char* job_string =
  22. "import time\n"
  23. "res = 0\n"
  24. "time.sleep(3)\n"
  25. "res = 100\n"
  26. "print('Huge job done!')\n"
  27. "print('Result:', res)\n";
  28. thrd_t thread1;
  29. thrd_create(&thread1, run_huge_job_in_vm1, job_string);
  30. for(int i = 0; i < 5; i++) {
  31. thrd_sleep(&(struct timespec){.tv_sec = 1, .tv_nsec = 0}, NULL);
  32. printf("main vm index: %d\n", py_currentvm());
  33. }
  34. int thrd_res;
  35. thrd_join(thread1, &thrd_res);
  36. printf("Thread result: %d\n", thrd_res);
  37. py_finalize();
  38. return 0;
  39. }