在带有pthreads的结构体中传递函数指针



我正在尝试用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 successfullyn");
  else
    printf("Errorn");
}

编译,但是在执行时,它完成时没有在屏幕上显示错误或消息。我错过了什么?

您的main线程在__fopen_t__完成之前退出。因此,要么使用pthread_detach分离该线程(fopen_t),然后做其他有用的事情,要么使用pthread_join等待__fopen_t__完成。

当使用pthread_join时,您的fopen_t可能看起来像,

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);
    pthread_join( thread, NULL );   // Waiting till the new thread completes
}

详细信息请参考手册pthread_detach和pthread_join。


更合乎逻辑的每R..在注释中,动态分配的代码如下:

#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>
struct fopen_struct {
    char *filename;
    char *mode;
    void *(*callback) (FILE *);
};
void *fopen_callback(FILE *);
pthread_t* fopen_t(void *(*callback)(FILE *), const char *, const char *);
void *__fopen_t__(void *);
// returns pthread_t* to be freed by caller
pthread_t* fopen_t(void *(*callback)(FILE *), const char *filename, const char *mode)
{
    struct fopen_struct *args = calloc( 1, sizeof(  struct fopen_struct ) );
    args->filename = filename;
    args->mode = mode;
    args->callback = callback;
    pthread_t *thread = calloc( 1, sizeof( pthread_t ) );   // Need error checks
    pthread_create( thread, NULL, &__fopen_t__, args);
    //pthread_join( thread, NULL ); // `thread` is returned to caller
    return thread;
}
// takes `struct fopen_struct*` as argument and will be freed
void *__fopen_t__(void *ptr) {
    struct fopen_struct *args = (struct fopen_struct *)ptr;
    FILE *result = fopen(args -> filename, args -> mode);
    args -> callback(result);
    free( args ); args = NULL;
    return NULL;
}
int main() {
    pthread_t *th_id = NULL;
    th_id = fopen_t(&fopen_callback, "test.txt", "r");      // Need error checks
    pthread_join( *th_id, NULL );  // Wait till the __fopen_t__ thread finishes
    free( th_id ); th_id = NULL;
    return 0;
}

在main的底部添加sleep()。也许你的程序在得到结果之前就完成了。

这是发现这个bug最简单的方法,但不是正确的方法。:)

最新更新