User Tools

Site Tools


c:pthreads:hello-world

Pthreads Hello World

hello.c
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
 
// This function will be executed by each thread
void *print_hello_world(void *tid) {
    // Print the thread's ID and a message
    printf("Hello World! Thread ID: %ld\n", (long)tid);
    pthread_exit(NULL);  // Exit the thread
}
 
int main(int argc, char *argv[]) {
    pthread_t threads[5]; // Array to store thread IDs
    int status;           // For storing return value of pthread_create
    long i;               // Loop variable
 
    // Create 5 threads
    for(i = 0; i < 5; i++) {
        printf("In main: creating thread %ld\n", i);
        // Create a new thread that will execute 'print_hello_world'
        status = pthread_create(&threads[i], NULL, print_hello_world, (void *)i);
 
        // Check for thread creation error
        if (status) {
            printf("Error in thread creation, return code: %d\n", status);
            exit(-1); // Exit if thread creation fails
        }
    }
 
    // Wait for all threads to complete
    for(i = 0; i < 5; i++) {
        pthread_join(threads[i], NULL);
    }
 
    printf("Program completed.\n");
    pthread_exit(NULL); // Exit the main thread
}

This program creates 5 threads, each displaying a 'Hello World' message and its ID.
After the creation of all the threads, the main program (main) waits for each thread to finish before it concludes. It's important to note that error handling and thread synchronization are critical aspects when working with pthreads, in order to avoid race conditions and other concurrency issues.

c/pthreads/hello-world.txt · Last modified: 2024/01/16 23:39 by odefta