In: Computer Science
// Filename: peterson_spinlock.c
#include <stdio.h>
#include <pthread.h>
#include"mythreads.h"
int flag[2];
const int MAX = 199;
int ans = 0;
int turn;
void lock_init()
{
flag[0] = flag[1] = 0;
turn = 0;
}
void lock(int self)
{
flag[self] = 1;
turn = 1-self;
while (flag[1-self]==1 && turn==1-self) ;
}
void unlock(int self)
{
flag[self] = 0;
}
void* func(void *s)
{
int i = 0;
int self = (int *)s;
printf("Thread Entered: %d\n", self);
lock(self);
for (i=0; i<MAX; i++)
ans++;
unlock(self);
}
// Driver code
int main()
{
pthread_t p1, p2;
lock_init();
pthread_create(&p1, NULL, func, (void*)0);
pthread_create(&p2, NULL, func, (void*)1);
pthread_join(p1, NULL);
pthread_join(p2, NULL);
printf("Actual Count: %d | Expected Count: %d\n",
ans, MAX*2);
return 0;
}
NoteApproch*
// Use
Filename: peterson_spinlock.c
// Initialize lock by reseting the both the threads to acquire the
locks. And, giving turn to one of them.
// Executed before entering critical section
// Set flag[self] = 1 saying you want to acquire lock
// But, first give the other thread the chance to
// acquire lock
// Wait until
the other thread looses the desire
// to acquire lock or it is your turn to get the lock.
// Executed after leaving critical section
// You do not desire to acquire lock in future.
// This will allow the other thread to acquire the lock.
// A Sample function run by two threads created in main()
// Critical section (Only one thread can enter here at a
time)
For Driver
code
// Initialized the lock then fork 2 threads
// Create two
threads (both run func)
// Wait for the threads to end.