#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;