Sample code for asynchronous programming in C
I need to program asynchronous ODBC driver,which need to handle user requested ODBC APIs 开发者_Python百科in asynchronous way. I am desperate to know how to write an asynchronous program portable on all platforms. Can you please provide me a basic C code on how to right asynchronous code?
Thanks in advance.
tidy code for asynchronous IO is a good thread to start in.
Portable solutions don't really exist. It also differs for socket streams and files, on all platforms.
libevent is a good abstraction.
Writing ODBC is not for the faint hearted.
Take below as example, notice async mostly used in multi-thread,
// FILE NAME: a.c
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <pthread.h>
typedef void (*pcb)(int a);
typedef struct parameter
{
int a;
pcb callback;
} parameter;
void *callback_thread(void *p1)
{
//do something
parameter *p = (parameter *)p1;
while (1)
{
printf("GetCallBack print! \n");
sleep(3); //delay 3s
p->callback(p->a);
}
}
extern int SetCallBackFun(int a, pcb callback)
{
printf("SetCallBackFun print! \n");
parameter *p = malloc(sizeof(parameter));
p->a = 10;
p->callback = callback;
pthread_t thing1;
pthread_create(&thing1, NULL, callback_thread, (void *)p);
pthread_join(thing1, NULL);
}
// FILE NAME: b.c
#include "boo.c"
#include <stdio.h>
void fCallBack(int a)
{
//do something
printf("a = %d\n",a);
printf("fCallBack print! \n");
}
int main(void)
{
SetCallBackFun(4,fCallBack);
return 0;
}
Output is below,
SetCallBackFun print!
GetCallBack print!
a = 10
fCallBack print!
GetCallBack print!
a = 10
fCallBack print!
GetCallBack print!
a = 10
fCallBack print!
GetCallBack print!
a = 10
fCallBack print!
GetCallBack print!
a = 10
fCallBack print!
GetCallBack print!
...
In terms of calling function, there are three types: sync, back, and async.
The tricky thing is the last two are highly correlated, why is that?
Perhaps a graph would make it clear, i.e.
精彩评论