Note that there are some explanatory texts on larger screens.

plurals
  1. POMulti-threaded random number generator keeps getting a SegFault at initstate_r function
    text
    copied!<p>I'm trying to develop a program in C that will generate a given number of random integers. It is supposed to use a given number of threads to speed this up. I found out that the regular random function won't work with threads and am now using random_r instead. I keep getting a SegFault at the initstate_r function, which doesn't make sense because I'm trying to initialize variables, not access them. Can anyone tell me what I'm doing wrong here? (The initstate_r function needs to stay in the generateRandomNumbers function.)</p> <p>Here is the code:</p> <pre><code>#include &lt;errno.h&gt; #include &lt;stdlib.h&gt; #include &lt;unistd.h&gt; #include &lt;stdio.h&gt; // must include stdio for pvm3.h to compile correctly #include &lt;sys/times.h&gt; /* for times system call */ #include &lt;sys/time.h&gt; /* for gettimeofday system call */ #include &lt;pthread.h&gt; /*#define DEBUG 1*/ #define RANDOM_SEED 12345678 //The main work routine //void generateRandomNumbers(long long); void *generateRandomNumbers(void *); double getMilliSeconds(); /* The main work routine */ //void generateRandomNumbers(long long int count) void *generateRandomNumbers(void *arg) { struct random_data buf; int32_t result; char rand_statebuf; printf("hold 1\n"); // This is the function that gives me a SegFault initstate_r(RANDOM_SEED, &amp;rand_statebuf, 128, &amp;buf); printf("hold 2\n"); long long int* count = (long long int*) arg; //printf("Count for thread ID# %ld is %lld\n", pthread_self(), *count); long long int i; //long int x; srandom_r(RANDOM_SEED, &amp;buf); for (i = 0; i &lt; *count; i++) { random_r(&amp;buf, &amp;result); #ifdef DEBUG printf("%ld\n", result); #endif } pthread_exit(NULL); } int main(int argc, char **argv) { long long int count, newCount; int numThreads; //pthread_t *tids; double timeStart = 0; double timeElapsed = 0; if (argc &lt; 3) { fprintf(stderr, "Usage: %s &lt;n&gt;\n" ,argv[0]); exit(1); } sscanf(argv[1],"%lld",&amp;count); /* lld for long long int */ sscanf(argv[2],"%d",&amp;numThreads); pthread_t tids[numThreads]; newCount = count/numThreads; timeStart = getMilliSeconds(); //And we are off int i; for (i=0; i&lt;numThreads; i++) { pthread_create(&amp;tids[i], NULL, generateRandomNumbers, (void *) &amp;newCount); //pthread_join(tids[i], NULL); } int j; for (j=0; j&lt;numThreads; j++) { pthread_join(tids[j], NULL); } //generateRandomNumbers(count); printf("generated %lld random numbers\n", count); timeElapsed = getMilliSeconds() - timeStart; printf("Elapsed time: %lf seconds\n",(double)(timeElapsed/1000.0)); fflush(stdout); exit(0); } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload