/* * uthread_yield * * Causes the currently running thread to yield use of the processor to * another thread. */ void uthread_yield(void) { /* Yield the processor to somebody */ /* Always succeeds */ /* When we call this function, the thread is not in CPU anymore */ int offset = ut_curthr - &uthreads[0]; /* Make sure it's not hack */ if (offset >= 0 && offset < UTH_MAX_UTHREADS && ut_curthr->ut_state == UT_ON_CPU) { ut_curthr->ut_state = UT_RUNNABLE; /* Set the priority */ if (uthread_setprio(ut_curthr->ut_id, ut_curthr->ut_prio) != 0) { char pbuffer[256] = {0}; sprintf(pbuffer, "error in setprio\n"); int ret = write(STDOUT_FILENO, pbuffer, strlen(pbuffer)); if (ret < 0) { perror("write"); } exit(EXIT_FAILURE); } } /* do switch */ uthread_switch(); }
int main(int ac, char **av) { int i; /* char buff[50]; memset(buff,0,50); sprintf(buff, "helloworld\n"); write(STDOUT_FILENO, buff, strlen(buff)); */ printf("hello\n"); uthread_init(); uthread_mtx_init(&mtx); uthread_cond_init(&cond); for (i = 0; i < NUM_THREADS; i++) { uthread_create(&thr[i], tester, i, NULL, 0); } uthread_setprio(thr[0], 2); for (i = 0; i < NUM_THREADS; i++) { char pbuffer[SBUFSZ]; int tmp, ret; uthread_join(thr[i], &tmp); sprintf(pbuffer, "joined with thread %i, exited %i.\n", thr[i], tmp); ret = write(STDOUT_FILENO, pbuffer, strlen(pbuffer)); if (ret < 0) { perror("uthreads_test"); return EXIT_FAILURE; } uthread_mtx_lock(&mtx); uthread_cond_signal(&cond); uthread_mtx_unlock(&mtx); } uthread_exit(0); return 0; }
/* * uthread_wake * * Wakes up the supplied thread (schedules it to be run again). * uthr: the pointer to the uthread object */ void uthread_wake(uthread_t *uthr) { assert(uthr != NULL && uthr->ut_state != UT_NO_STATE); /* Only wake up him if he is waiting! */ if (uthr->ut_state == UT_WAIT) { uthr->ut_state = UT_RUNNABLE; /* Put it into the appropriate queue */ if (uthread_setprio(uthr->ut_id, uthr->ut_prio) != 0) { char pbuffer[256] = {0}; sprintf(pbuffer, "error in setprio\n"); int ret = write(STDOUT_FILENO, pbuffer, strlen(pbuffer)); if (ret < 0) { perror("write"); } exit(EXIT_FAILURE); } } }