void *producer(void *producerId) { int *prodId; int r,i; prodId = (int *)producerId; // printf("Hello from *producer(thread) %d. \n Let's generate some numbers.\n",*prodId); for(i = 0; i < numberOfRandomNumbers; i++){ /*Locking mutex*/ rc = pthread_mutex_lock(&mutex); if (rc != 0){ printf("ERROR: return code from pthread_mutex_lock*() is %d \n",rc); pthread_exit(&rc); } //ελέγχει αν ο buffer είναι γεμάτος, αν είναι περιμένει να ελευθερωθεί θέση while(cb_isFull(cb) == 1){ rc = pthread_cond_wait(&bufferFull, &mutex); //περιμένει μέχρι να ελευθερωθεί θέση στον πίνακα if (rc != 0) { printf("ERROR: return code from pthread_cond_wait() is %d\n", rc); pthread_exit(&rc); } } r = rand_r(&seed) % 256; printf("Random number produced : %d \n", r); cb_push_back(cb, &r); // places the random number insider the buffer /*Unlocking mutex*/ rc = pthread_mutex_unlock(&mutex); if (rc != 0){ printf("ERROR: retrn code from pthread_mutex_lock*() is %d \n",rc); pthread_exit(&rc); } fprintf(fc, "Producer %d : %d \n",*prodId,r ); } pthread_exit(prodId); }
/** * Update row sum thread * @param row * @return */ void* update_row_sum(void* row) { int* r = (int*)row; int i; int sum = 0; for(i = 0; i < *r; i++) { sum += C[*r][i]; } //Sleep for some random seconds int sec = rand_r(&seeds[0][*r]) % 5 + 1; sleep(sec); //Mutual exclusion pthread_mutex_lock(&mp); if(sum > MAX_ROW_SUM) { MAX_ROW_SUM = sum; } pthread_mutex_unlock(&mp); }
/* Thread-safe, re-entrant version of rand_range(r) */ inline long rand_range_re(unsigned int *seed, long r) { int m = RAND_MAX; int d, v = 0; /* #ifdef BIAS_RANGE */ /* if(rand_r(seed) < RAND_MAX / 10000) { */ /* if(last < r || last > r * 10) { */ /* last = r; */ /* } */ /* return last++; */ /* } */ /* #endif */ do { d = (m > r ? r : m); v += 1 + (int)(d * ((double)rand_r(seed)/((double)(m)+1.0))); r -= m; } while (r > 0); return v; }
void randomTick(void) { static unsigned int seed = 0; static int changeSeed = 25; float fltran; if (changeSeed++ >= 25) { seed++; if (seed > 256) seed = 0; changeSeed = 0; } fltran = (float) (rand_r(&seed) / 30000.0); anglex = (anglex > 360.0) ? 0.0 : (anglex + fltran); angley = (angley > 360.0) ? 0.0 : (angley + fltran); anglez = (anglez > 360.0) ? 0.0 : (anglez + fltran); }
int net_dis_compile_gp (__do_base_h_enc packet) { struct timespec tp; if (-1 == clock_gettime (CLOCK_REALTIME, &tp)) { char eb[1024]; print_str ("ERROR: net_dis_compile_gp: clock_gettime failed: [%s]\n", strerror_r (errno, eb, sizeof(eb))); return 1; } packet->body.ts.tv_nsec = (uint32_t) tp.tv_nsec; packet->body.ts.tv_sec = (uint32_t) tp.tv_sec; packet->body.rand = (uint32_t) rand_r ((unsigned int*) &di_base.seed); return 0; }
static libgomp_lithe_context_t *__ctx_alloc(size_t stacksize) { libgomp_lithe_context_t *ctx = wfl_remove(&context_zombie_list); if (!ctx) { int offset = ROUNDUP(sizeof(libgomp_lithe_context_t), ARCH_CL_SIZE); offset += rand_r(&rseed(0)) % max_vcores() * ARCH_CL_SIZE; stacksize = ROUNDUP(stacksize + offset, PGSIZE); void *stackbot = mmap( 0, stacksize, PROT_READ|PROT_WRITE|PROT_EXEC, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0 ); if (stackbot == MAP_FAILED) abort(); ctx = stackbot + stacksize - offset; ctx->context.stack_offset = offset; ctx->context.context.stack.bottom = stackbot; ctx->context.context.stack.size = stacksize - offset; } return ctx; }
/** * randomized exponential backoff, stolen from Polite.hpp */ void backoff() { if (tries > 0 && tries <= MAX_BACKOFF_RETRIES) { // what time is it now unsigned long long starttime = getElapsedTime(); // how long should we wait (random) unsigned long delay = rand_r(&seed); delay = delay % (1 << (tries + MIN_BACKOFF)); // spin until /delay/ nanoseconds have passed. We can do // whatever we want in the spin, as long as it doesn't have // an impact on other threads unsigned long long endtime; do { endtime = getElapsedTime(); } while (endtime < starttime + delay); } tries++; }
/** * __xmlInitializeDict: * * This function is not public * Do the dictionary mutex initialization. * this function is not thread safe, initialization should * normally be done once at setup when called from xmlOnceInit() * we may also land in this code if thread support is not compiled in * * Returns 0 if initialization was already done, and 1 if that * call led to the initialization */ int __xmlInitializeDict(void) { if (xmlDictInitialized) return(1); if ((xmlDictMutex = xmlNewRMutex()) == NULL) return(0); xmlRMutexLock(xmlDictMutex); #ifdef DICT_RANDOMIZATION #ifdef HAVE_RAND_R rand_seed = time(NULL); rand_r(& rand_seed); #else srand(time(NULL)); #endif #endif xmlDictInitialized = 1; xmlRMutexUnlock(xmlDictMutex); return(1); }
static inline void print_el(active_ring_t *aring, active_el_t *el, char * buf, int len, int *poffset) { int offset = *poffset; int val = rand_r(aring->vseed); int bv; if (el->bias) { bv = ((val & 0xF) == 3); } else { bv = val & 0x1; } el->acc += bv; int rtn = snprintf(buf + offset, len - offset, "%" PRIu64 ",%u,%u\n", el->id, bv, el->bias); /* int rtn = snprintf(buf + offset, len - offset, "%" PRIu64 ",%u,%u,%u,%u\n", el->id, bv, el->bias, el->cnt, el->total);*/ *poffset = offset + rtn; }
static void submit_single_io(void) { uint64_t offset_in_ios; uint64_t start; int rc; struct ns_entry *entry = g_ns; uint64_t tsc_submit; offset_in_ios = rand_r(&seed) % entry->size_in_ios; start = spdk_get_ticks(); spdk_mb(); #if HAVE_LIBAIO if (entry->type == ENTRY_TYPE_AIO_FILE) { rc = aio_submit(g_ns->u.aio.ctx, &g_task->iocb, entry->u.aio.fd, IO_CMD_PREAD, g_task->buf, g_io_size_bytes, offset_in_ios * g_io_size_bytes, g_task); } else #endif { rc = spdk_nvme_ns_cmd_read(entry->u.nvme.ns, g_ns->u.nvme.qpair, g_task->buf, offset_in_ios * entry->io_size_blocks, entry->io_size_blocks, io_complete, g_task, 0); } spdk_mb(); tsc_submit = spdk_get_ticks() - start; g_tsc_submit += tsc_submit; if (tsc_submit < g_tsc_submit_min) { g_tsc_submit_min = tsc_submit; } if (tsc_submit > g_tsc_submit_max) { g_tsc_submit_max = tsc_submit; } if (rc != 0) { fprintf(stderr, "starting I/O failed\n"); } g_ns->current_queue_depth++; }
TEST(SequenceFileReaderTest, seek_to_tail_test) { toft::LocalFileSystem local; toft::File* file = local.Open("testdata/big_seq_file", "rw"); ASSERT_NE(static_cast<toft::File*>(NULL), file); toft::LocalSequenceFileReader reader(file); ASSERT_TRUE(reader.Init()); ASSERT_EQ(true, reader.Seek(80)); ASSERT_EQ(96, reader.Tell()); int tests[] = { -1, 0, 1, 2, 5, 10, 100, 1000, 2 * 1000, 3 * 1000, 5 * 1000, 10 * 1000, 100 * 1000, 200 * 1000, 300 * 1000, 0, 1, 2, 5 }; unsigned seed = getpid(); for (size_t i = 0; i < TOFT_ARRAY_SIZE(tests); ++i) { reader.Seek(rand_r(&seed) % (3 * 1024 * 1024)); EXPECT_TRUE(reader.SeekToTail(tests[i])); CheckReadNRecord(&reader, tests[i]); } }
void BubbleEmitter::SetBubbleParameter( BubbleActorPtr bubbleActor, unsigned int curUniform, const Vector2& emitPosition, const Vector2& direction, const Vector2& displacement ) { Vector2 dir(direction); int halfRange = displacement.x / 2; // for the y coordinate, always negative, so bubbles always go upwards Vector2 randomVec( rand_r( &mRandomSeed ) % static_cast<int>(displacement.x) - halfRange, -rand_r( &mRandomSeed ) % static_cast<int>(displacement.y) ); dir.Normalize(); randomVec.x -= dir.x*halfRange; randomVec.y *= 1.0f - fabsf(dir.x)*0.33f; if(randomVec.y > 0.0f) { randomVec.y *= 0.33f; } Vector4 startAndEndPos( emitPosition.x, emitPosition.y, emitPosition.x+randomVec.x, emitPosition.y+randomVec.y ); bubbleActor->SetStartAndEndPosition( curUniform, startAndEndPos ); bubbleActor->SetPercentage( curUniform, 0.f); }
void Backlock(){ struct timespec tim; tim.tv_sec = 0; int mindel = MINDELAY; int maxdel = MAXDELAY; int limit = mindel; unsigned int sp; srand(time(NULL)); while(1){ while(EBOlock){;} if(__sync_lock_test_and_set(&EBOlock,1) == 0) //if(__sync_fetch_and_or(&EBOstate, 1) == 0) return; else{//back off tim.tv_nsec = rand_r(&sp) % limit; limit = maxdel < (2 * limit) ? maxdel : (2 * limit); nanosleep(&tim, NULL); } } }
void extract_context(const vector<uint64_t>& sentence, size_t cur, unsigned window_size, unsigned* p_seed, vector<uint64_t>* context) { #ifndef UNIT_TEST unsigned actual_window_size = rand_r(p_seed) % window_size + 1; #else unsigned actual_window_size = window_size; (void) p_seed; #endif size_t begin = 0; if (cur > actual_window_size) { begin = cur - actual_window_size; } size_t end = cur + actual_window_size; if (end > sentence.size() - 1) { end = sentence.size() - 1; } for (size_t i = begin; i <= end; ++i) { if (i != cur) { context->push_back(sentence[i]); } } }
virtual void SetUp() { motor = new Motor(0); encoder = new Encoder(motor); encoder->setRandSeed(0); testRandSeed = 0; for(int i = 0; i < LOOPS_ACCELERATION; i++) { int randOutput = (rand_r(&testRandSeed) % 21) - 10; outputs[i] = randOutput/10.; } testRandSeed = 0; for(int i = 0; i < LOOPS_ACCELERATION; i++) { speeds[LOOPS_ACCELERATION - 1 - i] = getInstSpeed(&testRandSeed, outputs[i]); } testRandSeed = 0; }
const URLInfo* url_GetNext(RandState rand) { long randVal; if (urlCount == 0) { return NULL; } if (urlCount == 1) { return &(urls[0]); } #if HAVE_LRAND48_R lrand48_r(rand, &randVal); #elif HAVE_RAND_R randVal = rand_r(rand); #else randVal = rand(); #endif return &(urls[randVal % urlCount]); }
/*! Randomly lookup data in the hash */ static void *hash_test_lookup(void *d) { struct hash_test *data = d; int max; unsigned seed = time(NULL); /* ast_atomic_fetchadd_int provide a memory fence so that the optimizer doesn't * optimize away reads. */ while ((max = ast_atomic_fetchadd_int(&data->grow_count, 0)) < data->max_grow) { int i; char *obj; char *from_ao2; if (is_timed_out(data)) { return "Lookup timed out"; } if (max == 0) { /* No data yet; yield and try again */ sched_yield(); continue; } /* Randomly lookup one object from the hash */ i = rand_r(&seed) % max; obj = ht_new(i); if (obj == NULL) { return "Allocation failed"; } from_ao2 = ao2_find(data->to_be_thrashed, obj, OBJ_POINTER); ao2_ref(obj, -1); ao2_ref(from_ao2, -1); if (from_ao2 == NULL) { return "Key unexpectedly missing"; } } return NULL; }
int main( int argc, char ** argv ){ int opt; unsigned int numJobs = 10; unsigned int maxNumNodes = 4; unsigned int maxJobLength = 1000; unsigned int nodeNumSeed; unsigned int jobLengthSeed; while( (opt = getopt( argc, argv, "n:j:l:a:b:" )) != -1 ){ switch( opt ){ case 'n': maxNumNodes = atoi( optarg ); break; case 'j': numJobs = atoi( optarg ); break; case 'l': maxJobLength = atoi( optarg ); break; case 'a': nodeNumSeed = atoi( optarg ); break; case 'b': jobLengthSeed = atoi( optarg ); break; } } unsigned long long int counter = 0; for( ; counter < numJobs; counter ++ ){ printf( "%llu, %i, %i\n", counter, (rand_r( &jobLengthSeed ) % maxJobLength) + 1, (rand_r( &nodeNumSeed ) % maxNumNodes) + 1 ); } printf( "YYKILL" ); return 0; }
/*** Run a bunch of random transactions */ void bench_test(uintptr_t id, uint32_t* seed) { uint32_t loc[1024]; int snapshot[1024]; //determine the locations prior to the transaction for(uint32_t i = 0; i < CFG.ops; i++) { uint32_t r = rand_r(seed) % CFG.elements; local_mats[id][r]++; loc[i] = r; } TM_BEGIN(atomic) { for (uint32_t i = 0; i < CFG.ops; ++i) { snapshot[i] = TM_READ(matrix[loc[i]]); } for (uint32_t i = 0; i < CFG.ops; ++i) { TM_WRITE(matrix[loc[i]], 1 + snapshot[i]); } } TM_END; }
/* * Returns true iff a request to the given path should be delegated to the * proxy origin. */ static bool shouldProxyPath(const std::string& path) { ReadLock lock(s_proxyMutex); if (RuntimeOption::ProxyOriginRaw.empty()) return false; if (RuntimeOption::UseServeURLs && RuntimeOption::ServeURLs.count(path)) { return true; } if (RuntimeOption::UseProxyURLs) { if (RuntimeOption::ProxyURLs.count(path)) return true; if (matchAnyPattern(path, RuntimeOption::ProxyPatterns)) return true; } if (RuntimeOption::ProxyPercentageRaw > 0) { if ((abs(rand_r(&s_randState)) % 100) < RuntimeOption::ProxyPercentageRaw) { return true; } } return false; }
net_ctx_t * net_ctx_register( uint32_t ssrc, uint32_t initiator, char *ip_address, uint16_t port ) { uint8_t i; for( i = 0 ; i < _max_ctx ; i++ ) { if( ctx[i] ) { if( ctx[i]->used == 0 ) { time_t now = time( NULL ); unsigned int send_ssrc = rand_r( (unsigned int *)&now ); net_ctx_set( ctx[i], ssrc, initiator, send_ssrc, 0x638F, port, ip_address ); return ctx[i]; } } } logging_printf( LOGGING_WARN, "No free connection slots available\n"); return NULL; }
void *ping(void *s) { thread_init *p = s; /* p has the proper type instead of void */ int i; int sleep_time; char sync[1] = {'S'}; unsigned int rand_seed = p->my_seed; for (i = 0; i < p->count; i++) { sleep_time = 1 + (rand_r(&rand_seed) % p->max_sleep); printf("%s (Delay %d seconds before & after Pong thread)\n", p->my_call, sleep_time); st_sleep(sleep_time); BB_put(sync); st_sleep(sleep_time); /* give pong a chance to run */ } quit = true; printf("Ping exiting\n"); BB_put(sync); fflush(stdout); st_thread_exit(NULL); }
int parse_sentence(const string& sentence, const Vocabulary& vocab, real subsample_thres, unsigned* p_seed, vector<uint64_t>* words) { istringstream iss(sentence); uint64_t total_cnt = vocab.total_cnt(); int word_cnt = 0; string word; while (iss >> word) { uint64_t word_id; if (!vocab.find_word_id(word, &word_id)) { continue; } ++word_cnt; if (subsample_thres > 0) { double t = subsample_thres * total_cnt / vocab.get_word_cnt(word_id); double remain_prob = (sqrt(1 / t) + 1) * t; // not the same as the paper, which is sqrt(t) if (remain_prob < static_cast<real>(rand_r(p_seed)) / RAND_MAX) { continue; } } words->push_back(word_id); } return word_cnt; }
int main(int argc, char **argv) { int i; int nt = 0; if (argc > 1) { nt = atoi(argv[1]); } if (nt <= 0) nt = omp_get_num_procs(); # pragma omp parallel num_threads(nt) { int k = 0; int seed = 42; # pragma omp for for (i = 0; i < 12; i++) printf("%d(%d) %d %d\n", i, k++, omp_get_thread_num(), rand_r(&seed)); } return 0; }
int registry_uid_create(struct registry_instance *instance) { registry_lock(); // Find a good uid uint32_t new_uid; do { new_uid = rand_r(®istry_uid_seedp); } while (registry_uid_check(new_uid)); if (registry_uid_add(instance, new_uid) != POM_OK) { registry_unlock(); return POM_ERR; } registry_unlock(); return POM_OK; }
atable_ptr_t TableGenerator::int_random_weighted(size_t rows, size_t cols, size_t n, size_t h) { unsigned seed = (unsigned) clock(); atable_ptr_t new_table = create_empty_table(rows, cols); for (size_t col = 0; col < cols; ++col) { std::set<int64_t> values; while (values.size() < n) { int r = rand_r(&seed); values.insert(r); } OrderPreservingDictionary<int64_t> *dict = new OrderPreservingDictionary<int64_t>(); for (const auto & i: values) { dict->addValue(i); } new_table->setDictionaryAt(AbstractTable::SharedDictionaryPtr(dict), col); } new_table->resize(rows); for (size_t col = 0; col < cols; ++col) { for (size_t row = 0; row < rows; ++row) { ValueId v; v.valueId = selfsimilar(n, h); v.table = 0; new_table->setValueId(col, row, v); } } if (!_quiet) { std::cout << std::endl; } return new_table; }
void* singleint(void* inpBuf) { Barrier* Bar=((BufStruct*)inpBuf)->pBar; int id = ((BufStruct*)inpBuf)->id; int yolt; for (yolt=0; yolt<3;yolt++) { printf("START thread %3d\n",id); int G=0; int j=0; srand(rand()); unsigned int r = rand(); int iters = (1 + rand_r(&r) % 100) * POWER; if (id==1) { if (yolt==0) {iters=1;} if (yolt==1) {iters=1;} } for (j=0; j<iters; j++) { float x=rand()/1.0/RAND_MAX; float y=rand()/1.0/RAND_MAX; if (x*x+y*y<1) { G++; } } fflush(stdout); float res = 4*G/1.0/iters; printf("WAIT thread %3d (after %7d iterations)\n",id,iters); Bar->Sync(id); printf("DONE thread %3d. Result: %3.5f\n",id,res); } return NULL; }
int main(int argc, char **argv) { int n, scope; pthread_t t; pthread_attr_t attr; struct sched_param param; unsigned seed = 1; Pthread_attr_init(&attr); if (argc == 1) { printf("PTHREAD_SCOPE_PROCESS\n"); Pthread_attr_setscope(&attr, PTHREAD_SCOPE_PROCESS); } else { printf("PTHREAD_SCOPE_SYSTEM\n"); Pthread_attr_setscope(&attr, PTHREAD_SCOPE_SYSTEM); } Pthread_attr_getschedparam(&attr, ¶m); printf("sched_priority %d\n", param.sched_priority); Pthread_mutex_lock(&m); for (n = 0; n < 20; ++n) { param.sched_priority = rand_r(&seed) % 128; printf("creating thread %02d prio %02d\n", n, param.sched_priority); Pthread_attr_setschedparam(&attr, ¶m); Pthread_create(&t, &attr, Thread, (void *)n); } sleep(1); Pthread_mutex_unlock(&m); pthread_exit(NULL); }
struct connection *conn_get_server(struct context *ctx, uint16_t slot, int access) { struct address *addr; struct node_info info; bool readonly = false; if (slot_get_node_addr(slot, &info)) { addr = &info.nodes[0]; if (access != CMD_ACCESS_WRITE && config.readslave && info.index > 1) { int r = rand_r(&ctx->seed); if (!config.readmasterslave || r % info.index != 0) { int i = r % (info.index - 1); addr = &info.nodes[++i]; readonly = true; } } if (addr->port > 0) { return conn_get_server_from_pool(ctx, addr, readonly); } } return conn_get_raw_server(ctx); }
main() { int i; unsigned myseed; printf("seeding rand with 0x19610910: \n"); srand(0x19610910); printf("generating three pseudo-random numbers:\n"); for (i = 0; i < 3; i++) { printf("next random number = %d\n", rand()); } printf("generating the same sequence with rand_r:\n"); myseed = 0x19610910; for (i = 0; i < 3; i++) { printf("next random number = %d\n", rand_r(&myseed)); } return 0; }