Semaphore et modification de variable.
Bonjour à tous,
je suis entrain d'étudier le principe d'utilisation des semaphore, et j'ai fait un bou de code pour tester, mais je crois que ca ne fait pas exactement ce qu'il faudrait !
En fait j'ai 2 threads qui modifient chacun la meme valeur ( ici int n) et je mets donc en place un sémaphore pour que chacun leur tour ils modifient la valeur de n. Pouvez vous me dire si ce code est correct ?
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| #include "appli.h"
int n;
int main()
{
hSemaphore = CreateSemaphore(NULL,5,5,NULL);
hThread = CreateThread(NULL,NULL,ThreadProc,NULL,NULL,&ThreadId);
for(;;)
{
n=8;
printf("Thread Pere :\nn = %d\n", n);
Sleep(500);
ReleaseSemaphore(hSemaphore,1,NULL);
}
CloseHandle(hSemaphore);
return 0;
} |
Code:
1 2 3 4 5 6 7 8 9 10 11
| #include <windows.h>
#include <stdio.h>
#include <conio.h>
#include "thread.h"
HANDLE hSemaphore;
HANDLE hThread;
HANDLE ThreadId;
extern int n; |
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13
| #include "appli.h"
DWORD WINAPI ThreadProc(LPVOID lpParam)
{
for(;;)
{
n=2;
printf("Thread Fils :\nn = %d\n", n);
Sleep(500);
ReleaseSemaphore(hSemaphore,1,NULL);
}
return 0;
} |
Code:
DWORD WINAPI ThreadProc(LPVOID lpParam);
Merci.