• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

C++ rand_r函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了C++中rand_r函数的典型用法代码示例。如果您正苦于以下问题:C++ rand_r函数的具体用法?C++ rand_r怎么用?C++ rand_r使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了rand_r函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的C++代码示例。

示例1: pthread_mutex_lock

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);
}
开发者ID:MariosTheof,项目名称:Projects-in-C,代码行数:43,代码来源:proco2.c


示例2: update_row_sum

/**
 * 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);
}
开发者ID:stpddream,项目名称:OSHomework,代码行数:24,代码来源:main.c


示例3: rand_range_re

/* 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;
}
开发者ID:gramoli,项目名称:synchrobench,代码行数:20,代码来源:test.c


示例4: randomTick

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);
}
开发者ID:hiteshsathawane,项目名称:Cube-Rotation,代码行数:19,代码来源:vox.c


示例5: net_dis_compile_gp

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;
}
开发者ID:nixnodes,项目名称:glutil,代码行数:19,代码来源:net_dis.c


示例6: wfl_remove

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;
}
开发者ID:klueska,项目名称:libgomp-parlib,代码行数:20,代码来源:libgomp_lithe.c


示例7: backoff

      /**
       *  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++;
      }
开发者ID:shambakey1,项目名称:rstm_r5,代码行数:23,代码来源:WordBased.hpp


示例8: __xmlInitializeDict

/**
 * __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);
}
开发者ID:CMXWL,项目名称:libxml2,代码行数:32,代码来源:dict.c


示例9: print_el

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;
}
开发者ID:dylan-stark,项目名称:firehose,代码行数:20,代码来源:active.c


示例10: submit_single_io

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++;
}
开发者ID:spdk,项目名称:spdk,代码行数:41,代码来源:overhead.c


示例11: TEST

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]);
    }
}
开发者ID:acmol,项目名称:toft,代码行数:21,代码来源:local_sequence_file_reader_test.cpp


示例12: dir

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);
}
开发者ID:mettalla,项目名称:dali,代码行数:21,代码来源:bubble-emitter-impl.cpp


示例13: Backlock

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);
		}
	}
}
开发者ID:hriordan,项目名称:ParallelComputing,代码行数:21,代码来源:locks.c


示例14: extract_context

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]);
        }
    }
}
开发者ID:yong-wang,项目名称:word2vecPlus,代码行数:21,代码来源:word2vec.cpp


示例15: SetUp

	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;
	}
开发者ID:trdesilva,项目名称:Skunkworks-code-exercises-mentor,代码行数:21,代码来源:tests.cpp


示例16: url_GetNext

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]);
}
开发者ID:apigee,项目名称:apib,代码行数:21,代码来源:apib_url.c


示例17: main

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;
}
开发者ID:luisfnqoliveira,项目名称:sst-elements,代码行数:40,代码来源:jobGen.c


示例18: bench_test

/*** 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;
}
开发者ID:ml9951,项目名称:rstm,代码行数:23,代码来源:ReadWriteNBench.cpp


示例19: shouldProxyPath

/*
 * 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;
}
开发者ID:AmritanshuRanjan,项目名称:hhvm,代码行数:26,代码来源:http-request-handler.cpp


示例20: net_ctx_register

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;
}
开发者ID:alepom,项目名称:pimidi,代码行数:22,代码来源:net_connection.c



注:本文中的rand_r函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C++ rand_range函数代码示例发布时间:2022-05-30
下一篇:
C++ rand_norm函数代码示例发布时间:2022-05-30
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap