0% found this document useful (0 votes)
5 views2 pages

Multi Threading

The document contains a C program that creates and manages multiple threads using the pthread library. It defines a thread function that simulates work by printing messages and sleeping for a second in a loop. The main function creates five threads, waits for their completion, and then indicates that all threads have finished.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views2 pages

Multi Threading

The document contains a C program that creates and manages multiple threads using the pthread library. It defines a thread function that simulates work by printing messages and sleeping for a second in a loop. The main function creates five threads, waits for their completion, and then indicates that all threads have finished.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

#include <stdio.

h>

#include <stdlib.h>

#include <pthread.h>

#include <unistd.h>

#define NUM_THREADS 5

// Thread function (what each thread will run)

void* thread_function(void* arg) {

int thread_id = *(int*)arg;

printf("Thread %d: Started (TID: %lu)\n", thread_id, (unsigned long)pthread_self());

// Simulate some work

for (int i = 1; i <= 3; i++) {

printf("Thread %d: Working... step %d\n", thread_id, i);

sleep(1);

printf("Thread %d: Finished\n", thread_id);

pthread_exit(NULL); // same as: return NULL;

int main() {

pthread_t threads[NUM_THREADS];

int thread_ids[NUM_THREADS];

printf("Main thread: Creating %d threads...\n\n", NUM_THREADS);

// Create threads

for (int i = 0; i < NUM_THREADS; i++) {

thread_ids[i] = i + 1;

int rc = pthread_create(&threads[i], NULL, thread_function, &thread_ids[i]);


if (rc != 0) {

fprintf(stderr, "Error: pthread_create failed for thread %d (code %d)\n", i + 1, rc);

exit(EXIT_FAILURE);

// Wait for all threads to complete

for (int i = 0; i < NUM_THREADS; i++) {

pthread_join(threads[i], NULL);

printf("\nMain thread: All threads completed.\n");

return 0;

You might also like