ciao,
mi stavo chiedendo se nel momento in cui viene richiamata la funzione scrivifile() da parte di uno dei thread, era sufficiente racchiudere la chiamata scrivifile() tra
per evitare che gli n thread usino contemporanemanete la medesima funzione oppure si deve scrivere direttamente le chiamate alla funzione critica nella funzione stessa.codice:EnterCriticalSection(&CSector); scrivifile(); LeaveCriticalSection(&CSector);
Nel caso sopra sarebbe piuttosto comodo.
codice://* Use the -tWM (32-bit multi-threaded target) command-line switch for this example */ #pragma checkoption -tWM #include <windows.h> #include <process.h> #include <stdio.h> #define NTHREADS 25 CRITICAL_SECTION CSector; /* This function acts as the 'main' function for each new thread */ static unsigned __stdcall threadMain(void *arg) { EnterCriticalSection(&CSector); scrivifile(); LeaveCriticalSection(&CSector); return 0; } int main(void) { HANDLE hThreads[NTHREADS]; int i; unsigned threadId; SECURITY_ATTRIBUTES sa = { sizeof(SECURITY_ATTRIBUTES), /* structure size */ 0, /* No security descriptor */ TRUE /* Thread handle is inheritable */ }; /* Create NTHREADS inheritable threads that are initially suspended and that will run starting at threadMain()*/ for(i = 0; i < NTHREADS; i++) { hThreads[i] = (HANDLE)_beginthreadex( &sa, /* Thread security */ 4096, /* Thread stack size */ threadMain, /* Thread starting address */ (void *)i, /* Thread start argument */ CREATE_SUSPENDED, /* Create in suspended state */ &threadId); /* Thread ID */ if(hThreads[i] == INVALID_HANDLE_VALUE) { MessageBox(0, "Thread Creation Failed", "Error", MB_OK); return 1; } printf("Created thread %2d with an ID of %u\n", i, threadId); } printf("\nPress ENTER to thaw all threads\n\n"); getchar(); /* Resume the suspended threads */ for(i = 0; i < NTHREADS; i++) ResumeThread(hThreads[i]); InitializeCriticalSection(&CSector); /* Wait for the threads to run */ WaitForMultipleObjects(NTHREADS, hThreads, TRUE, INFINITE); /* Close all of the thread handles */ for(i = 0; i < NTHREADS; i++) CloseHandle(hThreads[i]); DeleteCriticalSection(&CSector); return 0; } /* ----------------------------------------------- */ void scrivifile() { FILE *fp; fp=fopen(); fprintf("test.txt","w"); fclose(fp); }

Rispondi quotando