Passing parameter to pthread

Posted by Andrei Ciobanu on Stack Overflow See other posts from Stack Overflow or by Andrei Ciobanu
Published on 2010-04-17T10:08:42Z Indexed on 2010/04/17 10:13 UTC
Read the original article Hit count: 259

Filed under:
|
|

Hello, i have the following code:

#include <stdlib.h>
#include <stdio.h>
#include <pthread.h>

#define NUM_THREADS 100

struct thread_param {
    char *f1;
    char *f2;
    int x;
};

void *thread_function(void *arg){
    printf("%d\n", ((struct thread_param*)arg)->x);
}

int main(int argc, char *argvs[]){
    int i, thread_cr_res = 0;
    pthread_t *threads;
    threads = malloc(100 * sizeof(*threads));
    if(threads == NULL){
        fprintf(stderr,"MALLOC THREADS ERROR");
        return (-1);
    }
    for(i = 0; i < NUM_THREADS; i++){
        struct thread_param *tp;
        if((tp = malloc(sizeof(*tp))) == NULL){
            fprintf(stderr,"MALLOC THREAD_PARAM ERROR");
            return (-1);
        }
        tp->f1 = "f1";
        tp->f2 = "f2";
        tp->x = i;
        thread_cr_res = pthread_create(&threads[i], 
                    NULL, 
                    thread_function, 
                    (void*)tp);
        if(thread_cr_res != 0){
            fprintf(stderr,"THREAD CREATE ERROR");
            return (-1);
        }
    }
    return (0);
}

What i want to achieve, is to print all the numbers from 0 to 99, from threads. Also i am experimenting a way to pass a structure as a thread input parameter.

What i am finding curios, is that not all the numbers are shown, eg:

 ./a.out | grep 9
9
19
29
39
49

And sometimes some numbers are shown twice:

...
75
74
89
77
78
79
91
91

Can you please explain me why is this happening ? No errors are shown.

© Stack Overflow or respective owner

Related posts about c

    Related posts about pthread