Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save jacobsapps/f3d3d310bb09a95b23bc64ec4d86aa8f to your computer and use it in GitHub Desktop.
Save jacobsapps/f3d3d310bb09a95b23bc64ec4d86aa8f to your computer and use it in GitHub Desktop.
#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