void ta_unlock(talock_t *mutex) { if(mutex->binary_sem.value == 1){ //if the lock is not locked, do nothing } else{ ta_sem_post(&mutex->binary_sem); } }
void reader(void *arg) { int tid = (int)arg; int val = 0; while (!stop) { ta_sem_wait(&writersem); ta_lock(&wmutex); int loc = readerloc; readerloc = (readerloc+1) % datalen; ta_unlock(&wmutex); val = data[loc]; ta_sem_post(&readersem); fprintf(stderr, "reader %d read location %d\n", tid, loc); if (random() % 2 == 0) ta_yield(); } }
void writer(void *arg) { fprintf(stderr,"in writer\n"); int tid = (int)arg; int val = 1000000; int writerloc = 0; while (!stop) { ta_sem_wait(&readersem); ta_lock(&rmutex); int loc = writerloc; writerloc = (writerloc+1) % datalen; ta_unlock(&rmutex); data[loc] = val++; ta_sem_post(&writersem); fprintf(stderr, "writer %d wrote location %d\n", tid, loc); if (random() % 2 == 0) ta_yield(); } }