void * Pthread(void *arg) { static Ns_Tls tls; /* * Allocate TLS first time (this is recommended TLS * self-initialization style. */ Ns_ThreadSetName("pthread"); sleep(5); if (tls == NULL) { Ns_MasterLock(); if (tls == NULL) { Ns_TlsAlloc(&tls, PthreadTlsCleanup); } Ns_MasterUnlock(); } Ns_TlsSet(&tls, arg); /* * Wait for exit signal from main(). */ Ns_MutexLock(&plock); while (!pgo) { Ns_CondWait(&pcond, &plock); } Ns_MutexUnlock(&plock); return arg; }
void MemThread(void *arg) { int i; void *ptr; Ns_ThreadSetName("memthread"); Ns_MutexLock(&lock); ++nrunning; Ns_CondBroadcast(&cond); while (!memstart) { Ns_CondWait(&cond, &lock); } Ns_MutexUnlock(&lock); ptr = NULL; for (i = 0; i < NA; ++i) { if (arg) { if (ptr) ns_free(ptr); ptr = ns_malloc(10); } else { if (ptr) free(ptr); ptr = malloc(10); } } }
void MemTime(int ns) { Ns_Time start, end, diff; int i; Ns_Thread *tids; tids = ns_malloc(sizeof(Ns_Thread *) * nthreads); Ns_MutexLock(&lock); nrunning = 0; memstart = 0; Ns_MutexUnlock(&lock); printf("starting %d %smalloc threads...", nthreads, ns ? "ns_" : ""); fflush(stdout); Ns_GetTime(&start); for (i = 0; i < nthreads; ++i) { Ns_ThreadCreate(MemThread, (void *) ns, 0, &tids[i]); } Ns_MutexLock(&lock); while (nrunning < nthreads) { Ns_CondWait(&cond, &lock); } printf("waiting...."); fflush(stdout); memstart = 1; Ns_CondBroadcast(&cond); Ns_MutexUnlock(&lock); for (i = 0; i < nthreads; ++i) { Ns_ThreadJoin(&tids[i], NULL); } Ns_GetTime(&end); Ns_DiffTime(&end, &start, &diff); printf("done: %d seconds, %d usec\n", (int) diff.sec, (int) diff.usec); }
void Ns_SemaWait(Ns_Sema *semaPtr) { Sema *sPtr = (Sema *) *semaPtr; Ns_MutexLock(&sPtr->lock); while (sPtr->count == 0) { Ns_CondWait(&sPtr->cond, &sPtr->lock); } sPtr->count--; Ns_MutexUnlock(&sPtr->lock); }
int Ns_CondTimedWait(Ns_Cond *cond, Ns_Mutex *mutex, Ns_Time *timePtr) { int err, status = NS_ERROR; struct timespec ts; if (timePtr == NULL) { Ns_CondWait(cond, mutex); return NS_OK; } /* * Convert the microsecond-based Ns_Time to a nanosecond-based * struct timespec. */ ts.tv_sec = timePtr->sec; ts.tv_nsec = timePtr->usec * 1000; /* * As documented on Linux, pthread_cond_timedwait may return * EINTR if a signal arrives. We have noticed that * EINTR can be returned on Solaris as well although this * is not documented. We assume the wakeup is truely * spurious and simply restart the wait knowing that the * ts structure has not been modified. */ do { err = pthread_cond_timedwait(GetCond(cond), NsGetLock(mutex), &ts); } while (err == EINTR); if (err == ETIMEDOUT) { status = NS_TIMEOUT; } else if (err != 0) { NsThreadFatal("Ns_CondTimedWait", "pthread_cond_timedwait", err); } else { status = NS_OK; } return status; }