CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 3 of 3
  1. #1
    Join Date
    Feb 2005
    Location
    Madrid (Spain)
    Posts
    511

    [RESOLVED] srand

    I'am thinking about synchronization and I begin with this code with the purpose to change it latter to insert a semaphore for example but this code not work fine... I think the trouble is with the initialization of srand...

    NOTE: main function only call Inicio function.

    Code:
    #define NTHREADS 10
    #define MAXCADENA 10
    
    void Inicio (void);
    
    char sCadena[MAXCADENA];
    
    int Aleatorio(int nMin, int nMax) {	
    	int nRes = nMin + rand() % ((nMax + 1) - nMin);
    	return nRes;
    }
    
    void WINAPI fx(void) {	
    	char c = Aleatorio(48, 90); // del 48 al 90 las letras
    	int nPos = Aleatorio(0, (MAXCADENA-1));
    	sCadena[nPos] = c;	
    }
    
    void Inicio (void) {
    
    	srand(time(NULL));
    	
    	for(int i=0;i<NTHREADS;i++) {
    		HANDLE h = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)fx, NULL, 0, 0);	
    		WaitForSingleObject(h, 100);
    	}
    
    	sCadena[MAXCADENA-1] = '\0';
    	
    	MessageBox(NULL, sCadena, "Cadena", MB_OK);
    }

  2. #2
    Join Date
    Oct 2002
    Location
    Austria
    Posts
    1,284

    Re: srand

    I think rand() is not thread safe. You could try to use rand_s() instead.
    Kurt

  3. #3
    Join Date
    Feb 2005
    Location
    Madrid (Spain)
    Posts
    511

    [Solved]Re: srand

    Thanks!!

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured