不同于其他高级语言,c语言层面没有try-catch的结构,本文通过使用c语言实现该功能的方式探究try-catch的技术原理
先聊一下setjmp和longjmp方法,在c语言中使用setjmp/longjmp实现从一个函数跳转到另外一个函数
使用方法
使用setjmp在代码上设置标签,当调用longjmp时,程序的执行从longjmp处跳转到setjmp设置标签处实现跨函数的跳转。另外在初次调用setjmp时,其返回值为0,如果使用longjmp设置后,程序跳转到setjmp设置的标签处同时,setjmp的返回值为longjmp设置的第二个参数。示例代码如下:
#include <stdio.h> #include <setjmp.h> jmp_buf buf; banana() { printf("in banana() \n"); longjmp(buf,1); /* 以下代码不会被执行 */ printf("you'll never see this, because i longjmp'd"); } main() { if(setjmp(buf)) printf("back in main\n"); else{ printf("first time through\n"); banana(); } }
接下来再引入一个技术,线程私有存储空间--pthread_key_t:
pthread_key_t无论是哪一个线程创建,其他所有的线程都是可见的,即一个进程中只需phread_key_create()一次。看似是全局变量,然而全局的只是key值,对于不同的线程对应的value值是不同的(通过pthread_setspcific()和pthread_getspecific()设置)。
线程私有变量示例代码如下:
#include <stdio.h> #include <string.h> #include <stdlib.h> #include <pthread.h> #define PTHREAD_COUNT 3 pthread_key_t key; typedef void* (*thread_cb)(void*); struct pair { int x; int y; }; void *thread1_proc(void *arg) { struct pair p = {1, 2}; int i = 0; while (++i < 100) { p.x ++; p.y ++; pthread_setspecific(key, &p); struct pair *res = (struct pair *)pthread_getspecific(key); printf("x: %d, y: %d\n", res->x, res->y); } } void *thread2_proc(void *arg) { int i = 0; while (++i < 100) { pthread_setspecific(key, &i); int *res = (int *)pthread_getspecific(key); printf("res: %d\n", *res); } } void *thread3_proc(void *arg) { int i = 0; while (++i < 100) { struct pair *res = (struct pair *)pthread_getspecific(key); printf("x: %d, y: %d\n", res->x, res->y); } } int main(int argc, char *argv[]) { pthread_key_create(&key, NULL); pthread_t thread_id[PTHREAD_COUNT] = {0}; thread_cb thread_proc[PTHREAD_COUNT] = { thread1_proc, thread2_proc, thread1_proc }; int i = 0; for (i = 0;i < PTHREAD_COUNT;i ++) { pthread_create(&thread_id[i], NULL, thread_proc[i], NULL); } for (i = 0;i < PTHREAD_COUNT;i ++) { pthread_join(thread_id[i], NULL); } pthread_key_delete(key); }
掌握了以上两种技术后,下面开始实现c语言版本的try-catch:
首先对线程私有变量的操作做宏定义
#define ntyThreadData pthread_key_t #define ntyThreadDataSet(key, value) pthread_setspecific((key), (value)) #define ntyThreadDataGet(key) pthread_getspecific((key)) #define ntyThreadDataCreate(key) pthread_key_create(&(key), NULL)
然后定义异常结构体
typedef struct _ntyExceptionFrame { jmp_buf env; int line; const char *func; const char *file; ntyException *exception; struct _ntyExceptionFrame *prev; char message[EXCEPTIN_MESSAGE_LENGTH+1]; } ntyExceptionFrame;
再然后,定义异常抛出的常用方法:
#define ntyExceptionPopStack \ ntyThreadDataSet(ExceptionStack, ((ntyExceptionFrame*)ntyThreadDataGet(ExceptionStack))->prev) #define ReThrow ntyExceptionThrow(frame.exception, frame.func, frame.file, frame.line, NULL) #define Throw(e, cause, ...) ntyExceptionThrow(&(e), __func__, __FILE__, __LINE__, cause, ##__VA_ARGS__, NULL)
#define Try do { \ volatile int Exception_flag; \ ntyExceptionFrame frame; \ frame.message[0] = 0; \ frame.prev = (ntyExceptionFrame*)ntyThreadDataGet(ExceptionStack); \ ntyThreadDataSet(ExceptionStack, &frame); \ Exception_flag = setjmp(frame.env); \ if (Exception_flag == ExceptionEntered) { #define Catch(e) \ if (Exception_flag == ExceptionEntered) ntyExceptionPopStack; \ } else if (frame.exception == &(e)) { \ Exception_flag = ExceptionHandled; #define Finally \ if (Exception_flag == ExceptionEntered) ntyExceptionPopStack; \ } { \ if (Exception_flag == ExceptionEntered) \ Exception_flag = ExceptionFinalized; #define EndTry \ if (Exception_flag == ExceptionEntered) ntyExceptionPopStack; \ } if (Exception_flag == ExceptionThrown) ReThrow; \ } while (0)
注意:为了满足实现try-catch的嵌套结构,使用一个单向链表,并实现先入先出从而实现try-catch的嵌套
下面是完整的测试代码
#include <stdio.h> #include <string.h> #include <stdlib.h> #include <stdarg.h> #include <pthread.h> #include <setjmp.h> #define ntyThreadData pthread_key_t #define ntyThreadDataSet(key, value) pthread_setspecific((key), (value)) #define ntyThreadDataGet(key) pthread_getspecific((key)) #define ntyThreadDataCreate(key) pthread_key_create(&(key), NULL) #define EXCEPTIN_MESSAGE_LENGTH 512 typedef struct _ntyException { const char *name; } ntyException; ntyException SQLException = {"SQLException"}; ntyException TimeoutException = {"TimeoutException"}; ntyThreadData ExceptionStack; typedef struct _ntyExceptionFrame { jmp_buf env; int line; const char *func; const char *file; ntyException *exception; struct _ntyExceptionFrame *prev; char message[EXCEPTIN_MESSAGE_LENGTH+1]; } ntyExceptionFrame; #define ntyExceptionPopStack \ ntyThreadDataSet(ExceptionStack, ((ntyExceptionFrame*)ntyThreadDataGet(ExceptionStack))->prev) #define ReThrow ntyExceptionThrow(frame.exception, frame.func, frame.file, frame.line, NULL) #define Throw(e, cause, ...) ntyExceptionThrow(&(e), __func__, __FILE__, __LINE__, cause, ##__VA_ARGS__, NULL) enum { ExceptionEntered = 0, ExceptionThrown, ExceptionHandled, ExceptionFinalized }; #define Try do { \ volatile int Exception_flag; \ ntyExceptionFrame frame; \ frame.message[0] = 0; \ frame.prev = (ntyExceptionFrame*)ntyThreadDataGet(ExceptionStack); \ ntyThreadDataSet(ExceptionStack, &frame); \ Exception_flag = setjmp(frame.env); \ if (Exception_flag == ExceptionEntered) { #define Catch(e) \ if (Exception_flag == ExceptionEntered) ntyExceptionPopStack; \ } else if (frame.exception == &(e)) { \ Exception_flag = ExceptionHandled; #define Finally \ if (Exception_flag == ExceptionEntered) ntyExceptionPopStack; \ } { \ if (Exception_flag == ExceptionEntered) \ Exception_flag = ExceptionFinalized; #define EndTry \ if (Exception_flag == ExceptionEntered) ntyExceptionPopStack; \ } if (Exception_flag == ExceptionThrown) ReThrow; \ } while (0) static pthread_once_t once_control = PTHREAD_ONCE_INIT; static void init_once(void) { ntyThreadDataCreate(ExceptionStack); } void ntyExceptionInit(void) { pthread_once(&once_control, init_once); } void ntyExceptionThrow(ntyException *excep, const char *func, const char *file, int line, const char *cause, ...) { va_list ap; ntyExceptionFrame *frame = (ntyExceptionFrame*)ntyThreadDataGet(ExceptionStack); if (frame) { frame->exception = excep; frame->func = func; frame->file = file; frame->line = line; if (cause) { va_start(ap, cause); vsnprintf(frame->message, EXCEPTIN_MESSAGE_LENGTH, cause, ap); va_end(ap); } ntyExceptionPopStack; longjmp(frame->env, ExceptionThrown); } else if (cause) { char message[EXCEPTIN_MESSAGE_LENGTH+1]; va_start(ap, cause); vsnprintf(message, EXCEPTIN_MESSAGE_LENGTH, cause, ap); va_end(ap); printf("%s: %s\n raised in %s at %s:%d\n", excep->name, message, func ? func : "?", file ? file : "?", line); } else { printf("%s: %p\n raised in %s at %s:%d\n", excep->name, excep, func ? func : "?", file ? file : "?", line); } } /* ** **** ******** **************** debug **************** ******** **** ** */ ntyException A = {"AException"}; ntyException B = {"BException"}; ntyException C = {"CException"}; ntyException D = {"DException"}; void *thread(void *args) { pthread_t selfid = pthread_self(); Try { Throw(A, "A"); } Catch (A) { printf("catch A : %ld\n", selfid); } EndTry; Try { Throw(B, "B"); } Catch (B) { printf("catch B : %ld\n", selfid); } EndTry; Try { Throw(C, "C"); } Catch (C) { printf("catch C : %ld\n", selfid); } EndTry; Try { Throw(D, "D"); } Catch (D) { printf("catch D : %ld\n", selfid); } EndTry; Try { Throw(A, "A Again"); Throw(B, "B Again"); Throw(C, "C Again"); Throw(D, "D Again"); } Catch (A) { printf("catch A again : %ld\n", selfid); } Catch (B) { printf("catch B again : %ld\n", selfid); } Catch (C) { printf("catch C again : %ld\n", selfid); } Catch (D) { printf("catch B again : %ld\n", selfid); } EndTry; } #define THREADS 50 int main(void) { ntyExceptionInit(); Throw(D, NULL); Throw(C, "null C"); printf("\n\n=> Test1: Try-Catch\n"); Try { Try { Throw(B, "recall B"); } Catch (B) { printf("recall B \n"); } EndTry; Throw(A, NULL); } Catch(A) { printf("\tResult: Ok\n"); } EndTry; printf("=> Test1: Ok\n\n"); printf("=> Test2: Test Thread-safeness\n"); #if 1 int i = 0; pthread_t threads[THREADS]; for (i = 0;i < THREADS;i ++) { pthread_create(&threads[i], NULL, thread, NULL); } for (i = 0;i < THREADS;i ++) { pthread_join(threads[i], NULL); } #endif printf("=> Test2: Ok\n\n"); }