CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 8 of 8

Threaded View

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

    [RESOLVED] Critical section

    Hi again.

    Now I'm trying to write a example of critical sections but it's not work. why?

    NOTE: main function only call Inicio function.

    Code:
    #define NTHREADS 500
    #define MAXCADENA 10
    #define MAXTIMESLEEP 50
    
    CRITICAL_SECTION CriticalSection_Cadena;
    
    void Inicio (void);
    char sCadena[MAXCADENA];
    int nNumero;
    
    int Aleatorio(int nMin, int nMax) {
    	UINT nNumero;	
    	rand_s(&nNumero);
    	int nRes = (UINT)((double)nNumero / (double) UINT_MAX * (double)nMax) + nMin;	
    	return nRes;
    }
    
    void WINAPI fx(void) {	
    	EnterCriticalSection(&CriticalSection_Cadena);
    
    		char c = Aleatorio(48, 90); // del 48 al 90 las letras
    		int nPos = Aleatorio(0, (MAXCADENA-1));	
    		sCadena[nPos] = c;	
    		nNumero = c;
    	
    	LeaveCriticalSection(&CriticalSection_Cadena);
    }
    
    void Inicio (void) {
    
    	srand(time(NULL));	
    	memset(sCadena, '-', sizeof(char) * MAXCADENA);
    
    	void (WINAPI *vfx[NTHREADS])(); // matriz de NTHREADS de punteros a funciones	
    	// Creamos las funciones
    	for(int i=0;i<NTHREADS;i++) {
    		vfx[i] = fx;
    	}
    
    	InitializeCriticalSection(&CriticalSection_Cadena);
    
    	HANDLE vhThread[NTHREADS];
    	// Abro los hilos
    	for(int i=0;i<NTHREADS;i++) {
    		vhThread[i] = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)vfx[i], NULL, 0, 0);		
    	}
    
    	WaitForMultipleObjects(NTHREADS, vhThread,  TRUE, INFINITE);
    	sCadena[MAXCADENA-1] = '\0';	
    
    	for(int i=0;i<NTHREADS;i++) {
    		CloseHandle(vhThread[i]);
    	}
    
    	DeleteCriticalSection(&CriticalSection_Cadena); 
    
    	MessageBox(NULL, sCadena, "Cadena", MB_OK);	
    }
    Last edited by juanpast; May 1st, 2012 at 04:06 AM.

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