Example of async call using C and setjmp and 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;
}