lundi 16 novembre 2020

generating random numbers using threads

I'm trying to generate a number of random floats between -1 and +1, the total amount is specified by the user as well as the amount of threads, the total amount of random numbers is then split equally between threads, the threads all use one workspace struct.

pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;

typedef struct WorkspaceStruct {
    unsigned int tid;
    int points_generated;
    int points_in_circle;
    unsigned int seed;
}Workspace;

void *worker(void *ws) {
    Workspace *workspace = (Workspace *) ws;  // link worker to workspace

    pthread_mutex_lock(&mutex);

    printf("Worker %d\n", workspace->tid);
    int max = workspace->points_generated;
    unsigned int seed = workspace->seed;
    for (int i = 0; i < max; ++i) {
        float point_x = (float)rand_r(&seed) / RAND_MAX * 2.0 - 1.0;
        float point_y = (float)rand_r(&seed) / RAND_MAX * 2.0 - 1.0;

        printf("x: %f, y: %f\n", point_x, point_y);
    }
    pthread_mutex_unlock(&mutex);

    pthread_exit(NULL);
}

void calculate_circle_area(int total_samples, int no_workers) {
    pthread_t worker_thread[no_workers];
    Workspace workspace;
    workspace.points_generated = total_samples / no_workers;
    workspace.tid = 0;
    workspace.seed = time(0);

    for (int i = 0; i < no_workers; ++i) {
        workspace.tid += 1;
        pthread_create(&worker_thread[i], NULL, worker, &workspace);
        pthread_join(worker_thread[i], NULL);
    }
}

int main(int argc, char *argv[]) {
    if (argc < 3) {
        printf("usage: ./program [no. of samples] [no. of worker threads]\n");
        return EXIT_FAILURE;
    } else {
        int total_samples = atoi(argv[1]);
        int no_workers = atoi(argv[2]);

        printf("\n");
        calculate_circle_area(total_samples, no_workers);

        printf("\n");
        return EXIT_SUCCESS;
    }
}

This works very partially, it does generate the random numbers and everything is split correctly, but each thread generates the same numbers, each numbers within the threads are different however.

example output for command: ./calc_area 9 3 (generate 9 randoms in total, using 3 threads)

Worker 1
x: 0.506291, y: -0.765927
x: -0.941786, y: -0.598265
x: 0.962658, y: -0.609824
Worker 2
x: 0.506291, y: -0.765927
x: -0.941786, y: -0.598265
x: 0.962658, y: -0.609824
Worker 3
x: 0.506291, y: -0.765927
x: -0.941786, y: -0.598265
x: 0.962658, y: -0.609824

I want each thread to generate different numbers from each other how can I do that? Thank you




Aucun commentaire:

Enregistrer un commentaire