-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path6.c
More file actions
58 lines (49 loc) · 1.57 KB
/
6.c
File metadata and controls
58 lines (49 loc) · 1.57 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
/*
============================================================================
Name : 6
Author : Piyush Singh
Description : Write a simple program to create three threads.
Date: 18th Sep, 2025.
============================================================================
*/
#include <stdio.h> // For printf()
#include <stdlib.h> // For exit()
#include <pthread.h> // For pthread_create(), pthread_join()
#include <unistd.h> // For sleep()
// Thread function — each thread runs this
void* thread_task(void* arg)
{
int thread_num = *(int*)arg; // Convert argument to int
printf("🧵 Thread %d is running\n", thread_num);
sleep(1); // Optional: simulate work
printf("✅ Thread %d has finished\n", thread_num);
return NULL;
}
int main()
{
pthread_t threads[3]; // Array to hold thread IDs
int thread_ids[3] = {1, 2, 3}; // Thread identifiers
// Step 1: Create 3 threads
for (int i = 0; i < 3; i++)
{
if (pthread_create(&threads[i], NULL, thread_task, &thread_ids[i]) != 0)
{
perror("❌ Failed to create thread");
exit(1);
}
}
// Step 2: Wait for all threads to finish
for (int i = 0; i < 3; i++)
pthread_join(threads[i], NULL);
printf("🎉 All threads have completed\n");
return 0;
}
// Output order may vary because threads run independently.
/*
Output:
./6 ─╯
🧵 Thread 2 is running!
🧵 Thread 1 is running!
🧵 Thread 3 is running!
✅ All threads finished.
*/