Created
May 5, 2025 09:09
-
-
Save pankajpansari/beade5a6f91d84b40a0d32db10348501 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
#include "types.h" | |
#include "user.h" | |
#include "thread.h" // Your thread library header | |
#define NUM_THREADS 2 | |
#define NUM_INCREMENTS 100000 // 100k increments per thread | |
// Shared global variable | |
volatile int shared_counter = 0; | |
// Declare a ticket lock | |
ticket_lock_t counter_lock; | |
// Worker function to increment the shared counter | |
void incrementer(void *arg) { | |
int thread_num = *(int*)arg; | |
printf(1, "Thread %d: Starting...\n", thread_num); | |
for (int i = 0; i < NUM_INCREMENTS; i++) { | |
// Acquire the lock before accessing shared data | |
ticket_lock_acquire(&counter_lock); | |
// Critical section - protected by the lock | |
shared_counter++; | |
// Release the lock | |
ticket_lock_release(&counter_lock); | |
} | |
printf(1, "Thread %d: Finished (%d increments).\n", thread_num, NUM_INCREMENTS); | |
} | |
int main(int argc, char *argv[]) { | |
int tids[NUM_THREADS]; | |
int args[NUM_THREADS]; | |
printf(1, "Main: Starting test with %d threads, %d increments each...\n", | |
NUM_THREADS, NUM_INCREMENTS); | |
// Initialize the ticket lock | |
ticket_lock_init(&counter_lock); | |
// Create threads | |
for (int i = 0; i < NUM_THREADS; i++) { | |
args[i] = i + 1; | |
thread_create(&tids[i], incrementer, &args[i]); | |
printf(1, "Main: Created thread %d\n", args[i]); | |
} | |
// Join threads | |
for (int i = 0; i < NUM_THREADS; i++) { | |
thread_join(tids[i]); | |
} | |
printf(1, "Main: All threads joined.\n"); | |
// Check final result | |
int expected_value = NUM_THREADS * NUM_INCREMENTS; | |
printf(1, "Main: Final counter value: %d\n", shared_counter); | |
printf(1, "Main: Expected counter value: %d\n", expected_value); | |
exit(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment