/** * Creates a case in which two threads will be racing to write one variable. Exected * x will not be equal to actual x for a large enough loop unless there are locks. */ int main(int argc, char *argv[]) { //Create 2 new threads. if(argc != 3){ printf(2, "Usage: condtest <loop count> <num consumers>\n"); exit(); } int pid; loops = atoi(argv[1]); numconsumers = atoi(argv[2]); //initialize locks and condition variables mutex_init(&mutex); cond_init(&empty); cond_init(&full); //create one producer pid = thread_create(&producer, (void *)"A"); //Thread 1: Add 1 to x printf(2, "Parent created producer with pid %d.\n", pid); int i; //create x number of consumers for (i = 0; i < numconsumers; i++){ pid = thread_create(&consumer, 0); mutex_lock(&print); printf(2, "Created consumer %d with pid %d.\n", i, pid); mutex_unlock(&print); } //wait for children for(i = 0; i < numconsumers+1; i++){ thread_wait(); } exit(); }
void cache_init (void) { int i; for (i = 0; i < CACHE_SIZE; i++) { lock_init (&block_cache[i].lock); cond_init (&block_cache[i].r_w_done); block_cache[i].old_sector = -1; block_cache[i].sector = -1; } //first block is preallocated for the free map. // it will not be evicted block_cache[0].sector = 0; block_cache[0].in_use = true; block_cache[0].IO_needed = true; cache_hand = 0; lock_init (&cache_lock); list_init (&read_ahead_queue); lock_init (&read_ahead_lock); cond_init (&read_ahead_go); thread_create ("write-behind", PRI_DEFAULT, write_behind_func, NULL); thread_create ("read_ahead", PRI_DEFAULT, read_ahead_func, NULL); }
/* readers/writer lock function for SunOS 4.1.x added by H.Nakagaki */ int rwlock_init(rwlock_t *rw, int c, void *d) { mutex_init(&(rw->lock), 0, 0); cond_init(&(rw->r_cond), &(rw->lock)); cond_init(&(rw->w_cond), &(rw->lock)); rw->readers = 0; }
static void init_file_synch (struct file_synch_status *fss) { lock_init (&fss->lock); lock_init (&fss->dir_lock); fss->writers_waiting = 0; fss->readers_running = 0; cond_init (&fss->read_cond); cond_init (&fss->write_cond); }
/* * Initializes the producer and consumer * monitor variables */ void init_producer_consumer(void) { /* monitor lock */ lock_init(&mutex); /* buffer conditions */ cond_init(¬_empty); cond_init(¬_full); }
int main(void) { report_start(START_CMPLT); //assuredly_misbehave((rand() % 521) % MISBEHAVE_MAX); misbehave(BGND_BRWN >> FGND_CYAN); // for landslide ERR(thr_init(STACK_SIZE)); ERR(mutex_init(&lock1)); ERR(mutex_init(&lock2)); ERR(cond_init(&cvar1)); ERR(cond_init(&cvar2)); ERR(thr_create(thread1, NULL)); report_misc("thread1 created"); /* Wait for thread1 to get to sleep on cvar1. */ mutex_lock(&lock1); while (!slept1) { mutex_unlock(&lock1); thr_yield(-1); mutex_lock(&lock1); } /* Indicate that we are about to signal */ signaled1 = 1; mutex_unlock(&lock1); /* Signal. Note that we know for sure that thread1 is asleep on * cvar1 (assuming correct cond vars and mutexes...) */ cond_signal(&cvar1); report_misc("cvar1 signaled"); //sleep(10); /* Now do it all again for the second set of things. */ /* Wait for thread1 to get to sleep on cvar2. */ mutex_lock(&lock2); while (!slept2) { mutex_unlock(&lock2); thr_yield(-1); mutex_lock(&lock2); } /* Indicate that we are about to signal */ signaled2 = 1; mutex_unlock(&lock2); /* Signal. Note that we know for sure that thread1 is asleep on * cvar1 (assuming correct cond vars and mutexes...) */ cond_signal(&cvar2); report_misc("cvar2 signaled"); /* We report success from the other thread. */ return 0; }
void reaction_init(struct reaction *reaction) { reaction->new_h_arrival = malloc(sizeof(struct condition)); reaction->reaction_occurred_h = malloc(sizeof(struct condition)); reaction->lck = malloc(sizeof(struct lock)); cond_init(reaction->new_h_arrival); cond_init(reaction->reaction_occurred_h); lock_init(reaction->lck); reaction->h_atoms = 0; }
/** @brief init a rwlock * * This function should initialize the lock pointed * to by rwlock. Effects of using a lock before it has been initialized may be * undefined. This function returns zero on success and a number less than * zero on error. * * @para rwlock: * @return error or success **/ int rwlock_init(rwlock_t *rwlock) { rwlock->rd_cnt= 0; rwlock->wr_cnt= 0; mutex_init(&rwlock->rdcnt_mutex); mutex_init(&rwlock->wrcnt_mutex); cond_init(&rwlock->rd_cond); cond_init(&rwlock->wr_cond); cond_init(&rwlock->writer_cond); return OK; }
void postfork1_child_tpool(void) { pthread_t my_tid = pthread_self(); tpool_t *tpool; tpool_job_t *job; /* * All of the thread pool workers are gone, except possibly * for the current thread, if it is a thread pool worker thread. * Retain the thread pools, but make them all empty. Whatever * jobs were queued or running belong to the parent process. */ top: if ((tpool = thread_pools) == NULL) return; do { tpool_active_t *activep; (void) mutex_init(&tpool->tp_mutex, USYNC_THREAD, NULL); (void) cond_init(&tpool->tp_busycv, USYNC_THREAD, NULL); (void) cond_init(&tpool->tp_workcv, USYNC_THREAD, NULL); (void) cond_init(&tpool->tp_waitcv, USYNC_THREAD, NULL); for (job = tpool->tp_head; job; job = tpool->tp_head) { tpool->tp_head = job->tpj_next; lfree(job, sizeof (*job)); } tpool->tp_tail = NULL; tpool->tp_njobs = 0; for (activep = tpool->tp_active; activep; activep = activep->tpa_next) { if (activep->tpa_tid == my_tid) { activep->tpa_next = NULL; break; } } tpool->tp_idle = 0; tpool->tp_current = 0; if ((tpool->tp_active = activep) != NULL) tpool->tp_current = 1; tpool->tp_flags &= ~TP_WAIT; if (tpool->tp_flags & (TP_DESTROY | TP_ABANDON)) { tpool->tp_flags &= ~TP_DESTROY; tpool->tp_flags |= TP_ABANDON; if (tpool->tp_current == 0) { delete_pool(tpool); goto top; /* start over */ } } } while ((tpool = tpool->tp_forw) != thread_pools); }
void bounded_buffer_init(bounded_buffer_t *b, size_t size) { b->buffer = (void **)mem_calloc(size, sizeof(void *)); b->size = size; b->count = 0; b->head = 0; b->tail = 0; mutex_init(&b->mutex); cond_init(&b->empty); cond_init(&b->fill); b->done = 0; b->workers = 0; mutex_init(&b->worker_mutex); }
void demux_reset(demux_t *dm) { demux_ent_t *ent; int proc_id; cond_init(&dm->next_chunk_cond); for(proc_id=0; proc_id < NUM_CHUNK_PROC; proc_id++) { ent = dm->entries + proc_id; if(ent->buf == NULL) ent->buf = kmalloc(DEMUX_BUF_SIZE, GFP_KERNEL); kfifo_init(&ent->fifo, ent->buf, DEMUX_BUF_SIZE); cond_init(&ent->fifo_full_cond); } }
o_con_t o_conInit(int dummy) { o_con_t c; c = (o_con_t)malloc( sizeof(cond_t) ); cond_init( c, USYNC_THREAD, NULL ); return c; }
Thread::Thread( char *name, void *context, void *(*action)(void *) ) { m_name = new char[ strlen(name) + 1 ]; strcpy( m_name, name ); m_context = context; m_action = action; // lock the registry ... add this thread to the registry if ( Thread::count == 0 ) { if ( mutex_init( &thread_mtx, USYNC_THREAD, NULL ) != 0 ) { printf( "Thread init fails: thread_mutex could not be created."); } if ( mutex_init( &barrier_mtx, USYNC_THREAD, NULL ) != 0 ) { printf( "Thread init fails: barrier_mutex could not be created."); } if ( cond_init( &barrier_cv, USYNC_THREAD, NULL ) != 0 ) { printf( "Thread init fails: condition var could not be created."); } barrier_count = 0; } if ( mutex_lock( &thread_mtx ) != 0 ) { printf( "Thread init fails: thread_mutex not allocated" ); } Thread::thread_count++; m_id = Thread::count++; Thread::registry[m_id] = this; if ( mutex_unlock( &thread_mtx ) != 0 ) { printf( "Thread init fails: thread_mutex could not unlock "); } m_procid = (processorid_t) -1; }
/* allocate and initialize group */ static vntsd_group_t * alloc_group(vntsd_t *vntsdp, char *group_name, uint64_t tcp_port) { vntsd_group_t *groupp; /* allocate group */ groupp = (vntsd_group_t *)malloc(sizeof (vntsd_group_t)); if (groupp == NULL) { vntsd_log(VNTSD_ERR_NO_MEM, "alloc_group"); return (NULL); } /* initialize group */ bzero(groupp, sizeof (vntsd_group_t)); (void) mutex_init(&groupp->lock, USYNC_THREAD|LOCK_ERRORCHECK, NULL); (void) cond_init(&groupp->cvp, USYNC_THREAD, NULL); if (group_name != NULL) { (void) memcpy(groupp->group_name, group_name, MAXPATHLEN); } groupp->tcp_port = tcp_port; groupp->listen_tid = (thread_t)-1; groupp->sockfd = (thread_t)-1; groupp->vntsd = vntsdp; D1(stderr, "t@%d alloc_group@%lld:%s\n", thr_self(), groupp->tcp_port, groupp->group_name); return (groupp); }
/*===========================================================================* * worker_init * *===========================================================================*/ PUBLIC void worker_init(struct worker_thread *wp) { /* Initialize worker thread */ if (!init) { threads_init(); if (mthread_attr_init(&tattr) != 0) panic("failed to initialize attribute"); if (mthread_attr_setstacksize(&tattr, TH_STACKSIZE) != 0) panic("couldn't set default thread stack size"); if (mthread_attr_setdetachstate(&tattr, MTHREAD_CREATE_DETACHED) != 0) panic("couldn't set default thread detach state"); pending = 0; init = 1; } ASSERTW(wp); wp->w_job.j_func = NULL; /* Mark not in use */ wp->w_next = NULL; if (mutex_init(&wp->w_event_mutex, NULL) != 0) panic("failed to initialize mutex"); if (cond_init(&wp->w_event, NULL) != 0) panic("failed to initialize conditional variable"); if (mthread_create(&wp->w_tid, &tattr, worker_main, (void *) wp) != 0) panic("unable to start thread"); yield(); }
int nscd_wait(nsc_ctx_t *ctx, nsc_db_t *nscdb, nsc_entry_t *entry) { waiter_t mywait; waiter_t *wchan = &nscdb->db_wait; (void) cond_init(&(mywait.w_waitcv), USYNC_THREAD, 0); mywait.w_key = entry; mywait.w_signaled = 0; mywait.w_next = wchan->w_next; mywait.w_prev = wchan; if (mywait.w_next) mywait.w_next->w_prev = &mywait; wchan->w_next = &mywait; (void) mutex_lock(&ctx->stats_mutex); ctx->stats.wait_count++; (void) mutex_unlock(&ctx->stats_mutex); while (!mywait.w_signaled) (void) cond_wait(&(mywait.w_waitcv), &nscdb->db_mutex); if (mywait.w_prev) mywait.w_prev->w_next = mywait.w_next; if (mywait.w_next) mywait.w_next->w_prev = mywait.w_prev; return (0); }
void cookie_cache_init(struct cookie_cache *c) { cookie_cache_state_init(&c->current); cookie_cache_state_init(&c->old); c->swap_time = poller_now; mutex_init(&c->lock); cond_init(&c->cond); }
int _pthread_cond_init(pthread_cond_t *cond, const pthread_condattr_t *cond_attr) { *cond = NULL; return (cond_init(cond, cond_attr)); }
static struct sml_control * control_start(struct frame_stack_range *range) { struct sml_control *control; assert(tlv_get_or_init(current_control) == NULL); control = xmalloc(sizeof(struct sml_control)); #ifndef WITHOUT_MULTITHREAD atomic_init(&control->state, ACTIVE(ASYNC)); mutex_init(&control->inactive_wait_lock); cond_init(&control->inactive_wait_cond); #endif /* !WITHOUT_MULTITHREAD */ control->frame_stack = range; range->next = NULL; control->thread_local_heap = NULL; control->exn_object = NULL; tlv_set(current_control, control); control_register(control); /* thread local heap is allocated after the control is set up. */ control->thread_local_heap = sml_heap_mutator_init(); return control; }
struct cache *cache_new(struct options *opts) { struct cache *c; c = xcalloc(1, sizeof(*c)); rwlock_init(&c->clock_lock); mutex_init(&c->mtx); cond_init(&c->condvar); c->clock = cpair_list_new(); c->table = cpair_htable_new(); c->opts = opts; gettime(&c->last_checkpoint); c->flusher = cron_new(flusher_cb, opts->cache_flush_period_ms); if (cron_start(c->flusher, (void*)c) != 1) { __PANIC("%s", "flushe cron start error, will exit"); goto ERR; } return c; ERR: xfree(c); return NULL; }
void simple_condwait(void) { unsigned long long start; mutex_t mutex; cond_t cond; struct cond_mutex cm = { .mutex = &mutex, .cond = &cond, }; thread_t cond_signaler_tid; fprintf(stderr, "%s\n", __FUNCTION__); check("mutex_init", mutex_init(&mutex, PTHREAD_MUTEX_DEFAULT, 0), 0); check("cond_init", cond_init(&cond, 0), 0); check("mutex_lock", mutex_lock(&mutex), 0); check("thread_spawn", thread_spawn(&cond_signaler_tid, 2, cond_signaler, &cm), 0); thread_msleep(11); start = rt_timer_tsc(); check("cond_wait", cond_wait(&cond, &mutex, XN_INFINITE), 0); check_sleep("cond_wait", start); thread_msleep(10); check("mutex_unlock", mutex_unlock(&mutex), 0); check("thread_join", thread_join(cond_signaler_tid), 0); check("mutex_destroy", mutex_destroy(&mutex), 0); check("cond_destroy", cond_destroy(&cond), 0); }
extern int camera_init (char *device_name, int camera_id) { union semun sem_un; unsigned short int sem_arr[] = { 1 }; // init semaphores if ((semid == -1) && (semid = semget (CAMERA_KEY + camera_id, 1, 0644)) == -1) { if ((semid = semget (CAMERA_KEY + camera_id, 1, IPC_CREAT | 0644)) == -1) { syslog (LOG_ERR, "semget %m"); // exit (EXIT_FAILURE); } else // we create a new semaphore { sem_un.array = sem_arr; if (semctl (semid, 0, SETALL, sem_un) < 0) { syslog (LOG_ERR, "semctl init: %m"); // exit (EXIT_FAILURE); } } } return cond_init (device_name, camera_id); }
void test_priority_condvar (void) { int i; /* This test does not work with the MLFQS. */ ASSERT (!thread_mlfqs); lock_init (&lock); cond_init (&condition); thread_set_priority (PRI_MIN); for (i = 0; i < 10; i++) { int priority = PRI_DEFAULT - (i + 7) % 10 - 1; char name[16]; snprintf (name, sizeof name, "priority %d", priority); thread_create (name, priority, priority_condvar_thread, NULL); } for (i = 0; i < 10; i++) { lock_acquire (&lock); msg ("Signaling..."); cond_signal (&condition, &lock); lock_release (&lock); } }
SLPError SLPOpen(const char *pcLang, SLPBoolean isAsync, SLPHandle *phSLP) { slp_handle_impl_t *hp; if (!pcLang || !phSLP) { return (SLP_PARAMETER_BAD); } /* allocate the handle */ if (!(hp = malloc(sizeof (*hp)))) { slp_err(LOG_CRIT, 0, "SLPOpen", "out of memory"); return (SLP_MEMORY_ALLOC_FAILED); } /* initialize outcall synchronization */ hp->pending_outcall = SLP_FALSE; (void) mutex_init(&(hp->outcall_lock), NULL, NULL); (void) cond_init(&(hp->outcall_cv), NULL, NULL); hp->close_on_end = SLP_FALSE; hp->consumer_tid = 0; /* locale property overrides argument */ if (!(hp->locale = SLPGetProperty(SLP_CONFIG_LOCALE))) { hp->locale = pcLang; } /* Make sure the language string is under our ownership */ if (!(hp->locale = strdup(hp->locale))) { free(hp); slp_err(LOG_CRIT, 0, "SLPOpen", "out of memory"); return (SLP_MEMORY_ALLOC_FAILED); } hp->cancel = 0; /* Asynchronous operation? */ if (isAsync) hp->async = SLP_TRUE; else hp->async = SLP_FALSE; /* TCP vars -- these are NULL until actually needed */ hp->tcp_lock = NULL; hp->tcp_wait = NULL; hp->tcp_ref_cnt = 0; /* Consumer / Producer pipe */ hp->q = NULL; /* Interface info, loaded on demand */ hp->ifinfo = NULL; /* force multicast, false by default */ hp->force_multicast = SLP_FALSE; /* internal call, false by default */ hp->internal_call = SLP_FALSE; *phSLP = hp; return (SLP_OK); }
/* * Wait on a condition. * * If the thread receives any exception while waiting CV, this * routine returns immediately with EINTR in order to invoke * exception handler. However, an application assumes this call * does NOT return with an error. So, the stub routine in a * system call library must call cond_wait() again if it gets * EINTR as error. */ int cond_wait(cond_t *cond, mutex_t *mtx, u_long timeout) { cond_t c; int err, rc; if (umem_copyin(cond, &c, sizeof(cond))) return DERR(EFAULT); sched_lock(); if (c == COND_INITIALIZER) { if ((err = cond_init(cond))) { sched_unlock(); return err; } umem_copyin(cond, &c, sizeof(cond)); } else { if (!cond_valid(c)) { sched_unlock(); return DERR(EINVAL); } } ASSERT(c->signal >= 0 && c->signal <= c->wait); c->wait++; if ((err = mutex_unlock_count(mtx))) { if (err < 0) { /* mutex was recursively locked - would deadlock */ mutex_lock(mtx); err = DERR(EDEADLK); } sched_unlock(); return err; } rc = sched_tsleep(&c->event, timeout); err = mutex_lock(mtx); c->wait--; if (!err) { if (c->signal) c->signal--; /* > 1 thread may be waiting */ else { switch (rc) { case SLP_TIMEOUT: err = ETIMEDOUT; break; case SLP_INTR: err = EINTR; break; default: /* unexpected */ err = DERR(EINVAL); } } } sched_unlock(); return err; }
/* Initializes the frame table. */ void frame_init() { hash_init(&frame_table, hash_frame, cmp_frame, NULL); random_init(0); lock_init(&ft_lock); /* Used by clock. */ lock_init(&clocklock); list_init(&clocklist); cond_init(&clockwaiting); lock_init(&clockcondlock); cond_init(&clockwaiting); clockrecieved = true; clockwaiters = 0; clockmodified = true; #ifdef CLOCK thread_create("clock.d", PRI_DEFAULT, clock_daemon, NULL); #endif }
Condition::Condition(void) { _mutex = MutexInit(); #if defined(POSIX_THREADS) _condition = malloc(sizeof(cond_t)); cond_init((cond_t *)_condition, USYNC_THREAD, NULL); #endif }
/** * @brief Initializes a thread group * * This function basically just initializes mutexes etc. * * @param eg An unitialized, but allocated, thread group to be initialized * @return 0 on success, nonzero otherwise * * @pre thr_init should have been called * @post eg is initialized */ int thrgrp_init_group(thrgrp_group_t *eg){ int ret; eg->zombie_in=NULL; eg->zombie_out=NULL; if((ret=mutex_init(&(eg->lock)))) return ret; if((ret=cond_init(&(eg->cv)))) return ret; return 0; }
int main(int argc, char ** argv) { int error; int i; int retcode; thrgrp_group_t tg; try(thr_init(7*1024)); try(mutex_init(&worldLock)); try(mutex_init(&updateLock)); try(cond_init(&updates)); try(cond_init(&gameOver)); initScreen(); thrgrp_init_group(&tg); try(thrgrp_create(&tg,update, 0)); try(thrgrp_create(&tg,controlThread, 0)); try(thrgrp_create(&tg,targetThread, 0)); try(thrgrp_create(&tg,scoreThread, 0)); /** finish drawing the screen **/ //scheduleUpdate(); /** lock down until the game finishes **/ mutex_lock(&worldLock); cond_wait(&gameOver, &worldLock); mutex_unlock(&worldLock); /** game is over **/ cond_signal(&updates); /** Once the game is over, cleanup after yourself! **/ for(i=0; i<NUM_THREADS; i++) { try(thrgrp_join(&tg, (void **)&retcode)); printf("Worker thread returned with code %d.\n",retcode); } thr_exit(0); return 0; }
static void dptf_init(void) { int id, t; for (id = 0; id < TEMP_SENSOR_COUNT; id++) for (t = 0; t < DPTF_THRESHOLDS_PER_SENSOR; t++) { dptf_threshold[id][t].temp = -1; cond_init(&dptf_threshold[id][t].over, 0); } }