sleep-sort.c

DownloadView Raw

/* File:       sleep-sort.c
 *
 * Purpose:    Demonstrates probably one of the most efficient and powerful
 *             parallel sorting algorithms known to humanity.
 *
 * Compile:    gcc -g -Wall -pthread -o sleep-sort sleep-sort.c
 * Run:        ./sleep-sort num-threads
 */

#include <math.h>
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/time.h>
#include <unistd.h>

struct thread_params {
    unsigned int rank;
    unsigned int to_sort;
};

void *worker_thread(void *arg)
{
    struct thread_params *params = arg;
    sleep(params->to_sort);
    printf("Thread %d -> %d\n", params->rank, params->to_sort);

    return NULL;
}

int main(int argc, char *argv[])
{
    if (argc <= 1) {
        fprintf(stderr, "Usage: %s num-threads\n", argv[0]);
        return EXIT_FAILURE;
    }

    srand(time(NULL));

    unsigned int num_threads = (unsigned int) strtol(argv[1], NULL, 10);

    printf("Generating unsorted list:\n");
    pthread_t *threads = malloc(num_threads * sizeof(pthread_t));
    for (int i = 0; i < num_threads; ++i) {
        struct thread_params *params = malloc(sizeof(struct thread_params));
        int r = (random() % 10) + 1;
        printf("%d\n", r);
        params->rank = i;
        params->to_sort = r;
        pthread_create(&threads[i], NULL, worker_thread, params);
    }
    printf(" -- Sorting! -- \n");

    for (int i = 0; i < num_threads; ++i) {
        pthread_join(threads[i], NULL);
    }

    return 0;
}