FKERN_API f8_bool ke_lock(HF8_KERNEL _kernel, int writeMode) { pthread_rwlock_fcfs_t * lk; if(writeMode && ke_get_flag(FKERN_KEY_LOCK)) { return f8_false; } lk = (pthread_rwlock_fcfs_t * )((struct kernel_t*)_kernel)->lock; if(writeMode) { pthread_rwlock_fcfs_gain_write(lk); } else { pthread_rwlock_fcfs_gain_read(lk); } return f8_true; }
void * reader_thread(void * void_context) { char id[100]; context_t * context; context = (context_t *)void_context; sprintf(id, "Reader %i", context->index); free(void_context); pthread_mutex_lock(&num_active_mutex); num_active_threads++; pthread_mutex_unlock(&num_active_mutex); while (!stop) { int which = rand()%3; if (which == 0) { pthread_rwlock_fcfs_gain_read(mylock PTHREAD_RWLOCK_FCFS_DEBUG_CALL_ARGS); usleep(rand()%1000000); pthread_rwlock_fcfs_release(mylock PTHREAD_RWLOCK_FCFS_DEBUG_CALL_ARGS); usleep(rand()%1000000); } else if (which == 1) { struct timeval now; struct timespec timeout; struct timezone tz; int ret; gettimeofday(&now, &tz); timeout.tv_nsec = (now.tv_usec + (rand()%1000000)); if (timeout.tv_nsec > 1000000) { timeout.tv_sec += timeout.tv_nsec / 1000000; timeout.tv_nsec %= 1000000; } timeout.tv_nsec *= 1000; ret = pthread_rwlock_fcfs_timed_gain_read( mylock, &timeout, NULL, NULL PTHREAD_RWLOCK_FCFS_DEBUG_CALL_ARGS ); usleep(rand()%1000000); if (ret == 0) { pthread_rwlock_fcfs_release(mylock PTHREAD_RWLOCK_FCFS_DEBUG_CALL_ARGS); } usleep(rand()%1000000); fflush(stdout); } else if (which == 2) { int ret; ret = pthread_rwlock_fcfs_try_gain_read(mylock PTHREAD_RWLOCK_FCFS_DEBUG_CALL_ARGS); usleep(rand()%1000000); if (ret == 0) { pthread_rwlock_fcfs_release(mylock PTHREAD_RWLOCK_FCFS_DEBUG_CALL_ARGS); } usleep(rand()%1000000); fflush(stdout); } } pthread_mutex_lock(&num_active_mutex); num_active_threads--; pthread_mutex_unlock(&num_active_mutex); return NULL; }