CS 220 Parallel Computing

global_hello.c

DownloadView Raw

/* File:
 *    thread_hello.c
 *
 * Purpose:
 *    Illustrate basic use of pthreads:  create some threads,
 *    each of which prints a message.
 *
 * Input:
 *    none
 * Output:
 *    message from each thread
 *
 * Compile:  gcc -g -Wall -o thread_hello thread_hello.c -pthread
 * Usage:
 *    ./thread_hello <thread_count>
 */

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

/* Global variable: accessible to all threads */
int num_threads;

long shared_number = 0;

pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;

void *hello(void * thread_number);

int main(int argc, char* argv[]) {

    if (argc != 2) {
        printf("usage: %s <number of threads>\n", argv[0]);
        return EXIT_SUCCESS;
    }

    num_threads = atoi(argv[1]);
    if (num_threads <= 0) {
        return EXIT_FAILURE;
    }

    pthread_t* thread_handles;
    thread_handles = malloc(num_threads * sizeof(pthread_t));

    int thread;
    for (thread = 0; thread < num_threads; thread++) {
        pthread_create(
                &thread_handles[thread],
                NULL,
                hello,
                (void *) (long) thread);
    }

    printf("Hello from the main thread\n");

    for (thread = 0; thread < num_threads; thread++) {
        pthread_join(thread_handles[thread], NULL);
    }

    printf("Shared number: %ld\n", shared_number);

    free(thread_handles);
    return 0;
}

void *hello(void* thread_number) {
    printf("Hello from thread %ld of %d\n", (long) thread_number, num_threads);
    for (int i = 0; i < 10000; ++i) {
        pthread_mutex_lock(&mutex);
        shared_number += 1;
        pthread_mutex_unlock(&mutex);
    }
    return NULL;
}