⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 jthread.c

📁 java virtual machince kaffe
💻 C
📖 第 1 页 / 共 5 页
字号:
               base += REDZONE;               currentJThread->stackBase = (void *) base;#endif       }}void*jthread_stacklimit(void){#if defined(STACK_GROWS_UP)        return (void*)((uintp)currentJThread->stackEnd - REDZONE);#else        return (void*)((uintp)currentJThread->stackBase + REDZONE);#endif}/* Spinlocks: simple since we're uniprocessor *//* ARGSUSED */voidjthread_spinon(void *arg UNUSED){       jthread_suspendall();}/* ARGSUSED */voidjthread_spinoff(void *arg UNUSED){       jthread_unsuspendall();}/* * yield to a thread of equal priority */voidjthread_yield(void){        intsDisable();        internalYield();        intsRestore();}/*       * sleep for time milliseconds */     voidjthread_sleep(jlong millis){        if (millis == 0) {                return;         }        intsDisable();	BLOCKED_ON_EXTERNAL(currentJThread);        suspendOnQThread(currentJThread, 0, (long)millis);        intsRestore();}/*  * Check whether a thread is alive. * * Note that threads executing their onstop function are not alive. */intjthread_alive(jthread *jtid){        int status = true;        intsDisable();        if (jtid == 0	    /* There seems to be a window in which death can be	     * broadcast before it is waited for.  Basically,	     * jthread_alive will be false immediately after	     * Thread.stop(), unless stopping the thread was	     * disabled.  Thread.alive() will become false as soon as	     * the thread is on its way out.	     */	    || (jtid->flags & (THREAD_FLAGS_DYING | THREAD_FLAGS_EXITING))	    || jtid->status == THREAD_DEAD)                status = false;        intsRestore();        return status;}/* * Change thread priority. */voidjthread_setpriority(jthread* jtid, int prio){	KaffeNodeQueue** ntid;	KaffeNodeQueue* last;	KaffeNodeQueue* node;	if (jtid->status == THREAD_SUSPENDED) {		jtid->priority = (unsigned char)prio;		return;	}	intsDisable();	/* Remove from current thread list */	last = NULL;	node = NULL;	for (ntid = &threadQhead[jtid->priority]; 		*ntid != 0; 		ntid = &(*ntid)->next) 	{		if (JTHREADQ(*ntid) == jtid) {			node = *ntid;			*ntid = node->next;			if (*ntid == 0) {				threadQtail[jtid->priority] = last;			}			break;		}		last = *ntid;	}	assert(node != NULL);	/* Insert onto a new one */	jtid->priority = (unsigned char)prio;	if (threadQhead[prio] == 0) {		threadQhead[prio] = node;		threadQtail[prio] = node;	}	else {		threadQtail[prio]->next = node;		threadQtail[prio] = node;	}	node->next = NULL;	/* If I was rescheduled, or something of greater priority was,	 * insist on a reschedule.	 */	if (jtid == currentJThread || prio > currentJThread->priority) {		needReschedule = true;	}	intsRestore();}/* * Stop a thread in its tracks. */voidjthread_stop(jthread *jtid){	intsDisable();	/* No reason to hit a dead man over the head */	if (jtid->status != THREAD_DEAD) {	  jtid->flags |= THREAD_FLAGS_KILLED;	}	/* if it's us, die */	if (jtid == jthread_current()	    && (jtid->flags & THREAD_FLAGS_DONTSTOP) == 0 && blockInts == 1)	  die();	/* We only have to resume the thread if it is not us. */	if (jtid != jthread_current())          resumeThread(jtid);	intsRestore();}/* * Have a thread exit.  This function does not return. */voidjthread_exit(void){	jthread* tid;	KaffeNodeQueue *liveQ;DBG(JTHREAD,	dprintf("jthread_exit %p\n", currentJThread);		);	jthread_disable_stop();	jmutex_lock(&threadLock);	talive--;	if (currentJThread->daemon)	  {	    tdaemon--;	  }	KaffeVM_unlinkNativeAndJavaThread();	assert(!(currentJThread->flags & THREAD_FLAGS_EXITING));	currentJThread->flags |= THREAD_FLAGS_EXITING;	jmutex_unlock(&threadLock);	jthread_enable_stop();	/* If we only have daemons left, then we should exit. */	if (talive == tdaemon) {	  	  DBG(JTHREAD,	      dprintf("all done, closing shop\n");	);	  	  if (runOnExit != 0) {	    runOnExit();	  }	  /* we disable interrupts while we go out to prevent a reschedule	   * in killThread()	   */	  intsDisable();	  	  for (liveQ = liveThreads; liveQ != 0; liveQ = liveQ->next) {	    tid = JTHREADQ(liveQ);	    /* The current thread is still on the live	     * list, and we don't want to recursively	     * suicide.	     */				    if (!(tid->flags & THREAD_FLAGS_EXITING) && tid != firstThread)	      killThread(tid);	  }	  if (currentJThread == firstThread)	  {	      DBG(JTHREAD,  dprintf("jthread_exit(%p): we're the main thread, returning.\n", currentJThread); );	      return;	  }	  /* Wake up the first thread */	  DBG(JTHREAD, dprintf("jthread_exit(%p): waking up main thread.\n", currentJThread));	  firstThread->suspender = NULL;	  resumeThread(firstThread);	} else if (currentJThread == firstThread) {	  /* The main thread is not exiting. Remove the flag to prevent	   * reschedule() from killing us. */	  intsDisable();	  currentJThread->flags &= ~THREAD_FLAGS_EXITING;	  currentJThread->suspender = NULL;	  suspendOnQThread(currentJThread, NULL, NOTIMEOUT);	  assert(talive == tdaemon);	  return;	}	/* we disable interrupts while we go out to prevent a reschedule	 * in killThread()	 */	intsDisable();	for (;;) {		killThread(currentJThread);		jthread_sleep((jlong) 1000);	}}/* * have main thread wait for all threads to finish */void jthread_exit_when_done(void){        while (talive > 1)		jthread_yield();	jthread_exit();}/* * Reschedule the thread. * Called whenever a change in the running thread is required. */voidreschedule(void){	int i;	jthread* lastThread;	int b;	/* A reschedule in a non-blocked context is half way to hell */	assert(intsDisabled());	b = blockInts;	for (;;) {	        for (i = max_priority; i >= min_priority; i--) {			if (threadQhead[i] == 0) 			    continue;			if (JTHREADQ(threadQhead[i]) != currentJThread) {				lastThread = currentJThread;				currentJThread = JTHREADQ(threadQhead[i]);				{					struct rusage ru;					jlong ct;					getrusage(RUSAGE_SELF, &ru);					ct = ((jlong)ru.ru_utime.tv_sec *					      1000000)						+ ((jlong)ru.ru_utime.tv_usec);					ct += ((jlong)ru.ru_stime.tv_sec *					       1000000)						+ ((jlong)ru.ru_stime.tv_usec);					lastThread->totalUsed +=						(ct - lastThread->startUsed);					currentJThread->startUsed = ct;				}DBG(JTHREADDETAIL,dprintf("switch from %p to %p\n", lastThread, currentJThread); );				/* save and restore floating point state */#if defined(SAVE_FP)				SAVE_FP(lastThread->fpstate);#endif#if defined(CONTEXT_SWITCH)				CONTEXT_SWITCH(lastThread, currentJThread);#else				if (JTHREAD_CONTEXT_SAVE(lastThread->env) == 0) {				    lastThread->restorePoint = 					GET_SP(lastThread->env);				    JTHREAD_CONTEXT_RESTORE(currentJThread->env, 1);				}#endif#if defined(LOAD_FP)				LOAD_FP(currentJThread->fpstate);#endif				/* Restore ints */				blockInts = b;				assert(currentJThread == lastThread);				/* Now handle external requests for cancelation				 * We do not act upon them if:				 * + The thread has the DONTSTOP flags set.				 * + The threads is already exiting				 */				if ((currentJThread->flags & 					THREAD_FLAGS_KILLED) != 0 && 				    (currentJThread->flags & 					THREAD_FLAGS_DONTSTOP) == 0 &&				    (currentJThread->flags & 					THREAD_FLAGS_EXITING) == 0 &&				    blockInts == 1) 				{					die();				}			}			/* Now kill the schedule */			needReschedule = false;			return;		}		/* since we set `wouldlosewakeup' first, we might write into		 * the pipe but not go to handleIO at all.  That's okay ---		 * all it means is that we'll return from the next select()		 * for no reason.  handleIO will eventually drain the pipe.		 */		wouldlosewakeup = 1;		if (sigPending) {			wouldlosewakeup = 0;			processSignals();			continue;		}#if defined(DETECTDEADLOCK)		if (tblocked_on_external == 0) {			ondeadlock();		}#endif		/* if we thought we should reschedule, but there's no thread		 * currently runnable, reset needReschedule and wait for another		 * event that will set it again.		 */		needReschedule = false;		handleIO(true);	}}/*============================================================================ *  * I/O interrupt related functions * *//* * resume all threads blocked on a given queue */static voidresumeQueue(KaffeNodeQueue *queue){	KaffeNodeQueue *tid;	KaffeNodeQueue *ntid;		for (tid = queue; tid != 0; tid = ntid) {		ntid = tid->next;		resumeThread(JTHREADQ(tid));	}}/* * Process incoming SIGIO * return 1 if select was interrupted */staticvoidhandleIO(int canSleep){	int r;	/** the wake-up time of the next thread on the alarm queue */	jlong firstAlarm;	/** how long do we want to sleep, at most */	jlong maxWait;	/* NB: both pollarray and rd, wr are thread-local */#if USE_POLL	/* for poll(2) */	unsigned int nfd, i;#if DONT_USE_ALLOCA	struct pollfd pollarray[FD_SETSIZE];	/* huge (use alloca?) */#else	struct pollfd *pollarray = alloca(sizeof(struct pollfd) * (maxFd+1));#endif#else	/* for select(2) */	fd_set rd;	fd_set wr;	struct timeval zero = { 0, 0 };	int i;#endif	int b = 0;	assert(intsDisabled());DBG(JTHREADDETAIL,	dprintf("handleIO(sleep=%d)\n", canSleep);		);#if USE_POLL	/* Build pollarray from fd_sets.	 * This is probably not the most efficient way to handle this.	 */	for (nfd = 0, i = 0; (int)i <= maxFd; i++) {		short ev = 0;		if (readQ[i] != 0) { 	/* FD_ISSET(i, &readsPending) */			/* Check for POLLIN and POLLHUP for portability.			 * Some poll(2) implementations return POLLHUP			 * on EOF.			 */			ev |= POLLIN | POLLHUP;		}		if (writeQ[i] != 0) {   /* FD_ISSET(i, &writesPending) */			ev |= POLLOUT;			assert(FD_ISSET(i, &writesPending));		}		if (ev != 0) {			pollarray[nfd].fd = i;			pollarray[nfd].events = ev;			nfd++;		}	}#else	FD_COPY(&readsPending, &rd);	FD_COPY(&writesPending, &wr);#endif	/*	 * figure out which fds are ready	 */retry:	if (canSleep) {		b = blockInts;		/* NB: BEGIN unprotected region */		blockInts = 0;		/* add sigpipe[0] if needed */#if USE_POLL		pollarray[nfd].fd = sigPipe[0];		pollarray[nfd].events = POLLIN;		nfd++;#else		FD_SET(sigPipe[0], &rd);#endif	}        /*	 * find out if we have any threads waiting (and if so, when the first	 * one will expire).  we use this to prevent indefinite waits in the	 * poll / select	 *	 */	firstAlarm = -1;	if (alarmList != 0) {		// sorted		firstAlarm = JTHREADQ(alarmList)->time;	}	maxWait = (canSleep ? -1 : 0);	if ( (firstAlarm != -1) && (canSleep) ) {		jlong curTime = currentTime();		if (curTime >= firstAlarm) {			maxWait = 0;		} else {			maxWait = firstAlarm - curTime;		}		DBG(JTHREADDETAIL, dprintf("handleIO(sleep=%d) maxWait=%ld\n", canSleep, (long) maxWait); );	}#if USE_POLL	r = poll(pollarray, nfd, maxWait);#else	if (maxWait <= 0) {		r = select(maxFd+1, &rd, &wr, 0, &zero);	} else {		struct timeval maxWaitVal = { maxWait/1000, (maxWait % 1000) * 1000 };		r = select(maxFd+1, &rd, &wr, 0, &maxWaitVal);	}#endif	/* Reset wouldlosewakeup here */	wouldlosewakeup = 0; 	if (canSleep) {		int can_read_from_pipe = 0;		blockInts = b;		/* NB: END unprotected region */#if USE_POLL		can_read_from_pipe = (pollarray[--nfd].revents & POLLIN);#else		can_read_from_pipe = FD_ISSET(sigPipe[0], &rd);#endif		/* drain helper pipe if a byte was written */		if (r > 0 && can_read_from_pipe) {			char c;			/* NB: since "rd" is a thread-local variable, it can 			 * still say that we should read from the pipe when 			 * in fact another thread has already read from it.			 * That's why we count how many bytes go in and out.			 */			if (bytesInPipe > 0) {				read(sigPipe[0], &c, 1);				bytesInPipe--;			}		}		if (sigPending) {			processSignals();		}	}	if ((r < 0 && errno == EINTR) && !canSleep) 		goto retry;	if (r <= 0)		return;DBG(JTHREADDETAIL,	dprintf("Select returns %d\n", r);			);#if USE_POLL	for (i = 0; r > 0 && i < nfd; i++) {		int fd;		register short rev = pollarray[i].revents;		if (rev == 0) {			continue;		}		fd = pollarray[i].fd;		needReschedule = true;		r--;		/* If there's an error, we don't know whether to wake		 * up readers or writers.  So wake up both if so.		 * Note that things such as failed connect attempts		 * are reported as errors, not a read or write readiness.		 */		/* wake up readers when not just POLLOUT */		if (rev != POLLOUT && readQ[fd] != 0) {			resumeQueue(readQ[fd]);			readQ[fd] = 0;		}		/* wake up writers when not just POLLIN */

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -