Created
June 20, 2025 07:36
-
-
Save jacobsapps/f3d3d310bb09a95b23bc64ec4d86aa8f to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#import <stdio.h> | |
#import <stdlib.h> | |
#import <pthread.h> | |
#import <unistd.h> // for sleep() | |
pthread_mutex_t printLock; | |
void* countdown(void* arg) { | |
int id = *((int*)arg); | |
for (int i = 5; i >= 1; i--) { | |
pthread_mutex_lock(&printLock); | |
printf("Thread %d: %d\n", id, i); | |
pthread_mutex_unlock(&printLock); | |
sleep(1); // simulate work | |
} | |
return NULL; | |
} | |
int main() { | |
pthread_t t1, t2; | |
int id1 = 1, id2 = 2; | |
// Initialize mutex | |
if (pthread_mutex_init(&printLock, NULL) != 0) { | |
printf("Failed to initialize mutex\n"); | |
return 1; | |
} | |
printf("Starting threads...\n"); | |
pthread_create(&t1, NULL, countdown, &id1); | |
pthread_create(&t2, NULL, countdown, &id2); | |
pthread_join(t1, NULL); | |
pthread_join(t2, NULL); | |
pthread_mutex_destroy(&printLock); | |
printf("All threads completed.\n"); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment