Intel® C++ Compiler
Community support and assistance for creating C++ code that runs on platforms based on Intel® processors.
7942 Discussions

Is rand() function reentrant / thread safe ? Why rand_r doesn't exist in intel's c standard lib?

mikeitexpert
New Contributor II
3,710 Views

I just need a random number generator like rand(); however, it needs to be reentrant / thread safe. 

I am using OpenMP for parallelization. I am wondering if there is an implementation for rand_r(int) in intel's standard c library? If no what is the replacement ? 

I tired to build the below example but failed ... 

#include <stdlib.h>

int main(){
	int seed1 = 1;
	printf("rand = %d\n", rand_r(&seed1));
}

 

I am using icl.exe and below is the error message.

C:\Users\Mehdi-laptop\workspace_v9_2_1\ark_cpplab>icl test.c
Intel(R) C++ Intel(R) 64 Compiler for applications running on Intel(R) 64, Version 19.1.2.254 Build 20200623
Copyright (C) 1985-2020 Intel Corporation.  All rights reserved.

test.c
Microsoft (R) Incremental Linker Version 14.00.24215.1
Copyright (C) Microsoft Corporation.  All rights reserved.

-out:test.exe
test.obj
test.obj : error LNK2019: unresolved external symbol rand_r referenced in function main
test.exe : fatal error LNK1120: 1 unresolved externals

 

Any hint or clue is much appreciate it.

Regards

0 Kudos
3 Replies
Gopika_Intel
Moderator
3,685 Views

Hi,

 

Thank you for posting in Intel C++ Forum. rand_r is available in linux. You are right, the function rand() is not reentrant or thread-safe, since it uses hidden state that is modified on each call. To make it thread safe, a combination of current time and current thread number can be used. Below is the code.

 

 

 

#pragma omp parallel
	  {
		srand(time(NULL)^ omp_get_thread_num());
		#pragma omp for
		
		for (int i = 0; i < 10; ++i)
		  printf("\n%d",rand());
	  }

In order to generate random numbers, srand is usually initialized to some distinctive runtime value, like the value returned by function time. For every different seed value used in a call to srand, the pseudo-random number generator can be expected to generate a different succession of results in the subsequent calls to rand.

 

Hope this helps

Regards

Gopika

 

0 Kudos
Gopika_Intel
Moderator
3,662 Views

Hi,

We haven’t heard from you in a while. Did the solution work for you? Can we discontinue monitoring this thread? Let us know your updates.

Regards

Gopika


0 Kudos
Gopika_Intel
Moderator
3,639 Views

Hi,

We have not heard from you in a while. If you need any additional information, please submit a new question as this thread will no longer be monitored.

Regards

Gopika


0 Kudos
Reply