c_cpp 使用C和setjmp和longjmp进行异步调用的示例

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了c_cpp 使用C和setjmp和longjmp进行异步调用的示例相关的知识,希望对你有一定的参考价值。

#include <stdio.h>
#include <stdlib.h>
#include <setjmp.h>
#include <unistd.h>
#include <pthread.h>

/*Async style call example in C*/

// Used for threads NOTE the starting value is zero.
static int TOTAL = 0;

// Used for async style return
static jmp_buf ENVBUF;

// The function a thread is invoked with.
void* threadJob(void *vargp)
{
    sleep(4);
    puts("Done sleeping"); // This statement doesn't get called, as the call is async.
    TOTAL += 300;
    return NULL;
}

//This function orchestrates the workers 
void callWorkers(void)
{
  pthread_t worker1;
  pthread_t worker2;
  
  // Starts the workers, 
  pthread_create(&worker1, NULL, threadJob, NULL);
  pthread_create(&worker2, NULL, threadJob, NULL);
  
  // jumps out of the current stack frame, hence not waiting for the threads to finish.
  longjmp(ENVBUF, 1);
}

int main(void) {
  
  pthread_t worker;
  
  if(setjmp(ENVBUF)) // This only runs after longjmp is called. 
  {
    
    printf("async calls commenced, total is still %d\n", TOTAL);
    exit(0);
  }
  else
  {
    printf("Calling worker threads, total is now %d\n", TOTAL);
    callWorkers();
  }
  return 0;
}

以上是关于c_cpp 使用C和setjmp和longjmp进行异步调用的示例的主要内容,如果未能解决你的问题,请参考以下文章

C setjmp和longjmp

setjmp和longjmp简介

使用 longjmp/setjmp 进行 C 错误处理都有哪些“好”方法?

setjmp和longjmp浅析

setjmp和longjmp浅析

(C)非局部跳转语句(setjmp和longjmp)