Thread: pthreads join problem

  1. #1
    Registered User
    Join Date
    Jun 2013
    Jodhpur, India

    Question pthreads join problem

    I am trying to emulate callback mechanism in C. The code I have is follows:

    #include <stdio.h>
    #include <pthread.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 *);
    pthread_t 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 ??
        return thread;
    void *__fopen_t__(void *ptr) {
        printf("I am done!\n");
        struct fopen_struct *args = (struct fopen_struct *)ptr;
        FILE *result = fopen(args -> filename, args -> mode);
        args -> callback(result);
    int main() {
        pthread_t thread = fopen_t(&fopen_callback, "test.txt", "r");
        //pthread_join ??
    void *fopen_callback(FILE *stream) {
        if (stream != NULL)
            printf("Opened file successfully\n");
    If I do a pthread_join in fopen_t() it works perfectly fine. But if I do that in main() I get a segmentation fault error. I want to call it in main() because I want it to be non-blocking, is there any solution?

  2. #2
    "I Win!" by U. Lose vart's Avatar
    Join Date
    Oct 2006
    Rishon LeZion, Israel
    in line 20 you are passing pointer to local var args to pthread_create

    you fopen_t could exit before __fopen_t__ will read this memory
    as a result __fopen_t__ will access uninitialized memory.

    you need to use malloc to allocate args in fopen_t and free it in the __fopen_t__ after the data was read from the struct
    To be or not to be == true

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. How to join this two together?
    By SuperMiguel in forum C Programming
    Replies: 7
    Last Post: 06-20-2012, 02:01 AM
  2. Euler Problem 10 With pthreads
    By deadrabbit in forum C Programming
    Replies: 6
    Last Post: 12-31-2011, 05:04 AM
  3. pthreads/arrays Problem
    By Jedel in forum C Programming
    Replies: 3
    Last Post: 10-15-2009, 07:21 AM
  4. Pthreads problem
    By maluyk in forum C Programming
    Replies: 4
    Last Post: 04-27-2007, 09:33 AM

Tags for this Thread