我正在尝试使用 pthreads 在 C 中模拟回调机制。我的代码如下:
#include <stdio.h>
#include <pthread.h>
struct fopen_struct {
char *filename;
char *mode;
void *(*callback) (FILE *);
};
void *fopen_callback(FILE *);
void fopen_t(void *(*callback)(FILE *), const char *, const char *);
void *__fopen_t__(void *);
void fopen_t(void *(*callback)(FILE *), const char *filename, const char *mode) {
struct fopen_struct args;
args.filename = filename;
args.mode = mode;
args.callback = callback;
pthread_t thread;
pthread_create(&thread, NULL, &__fopen_t__, &args);
}
void *__fopen_t__(void *ptr) {
struct fopen_struct *args = (struct fopen_struct *)ptr;
FILE *result = fopen(args -> filename, args -> mode);
args -> callback(result);
}
int main() {
fopen_t(&fopen_callback, "test.txt", "r");
}
void *fopen_callback(FILE *stream) {
if (stream != NULL)
printf("Opened file successfully\n");
else
printf("Error\n");
}
这会编译,但在执行时,它会在屏幕上没有错误或消息的情况下完成。我错过了什么?