Suppose I have a piece of code that must not be executed concurrently. My (presumed naive) approach at attempting a thread lock would look something like this:
int lock = 0;
DWORD WINAPI ThreadProc(LPVOID lpParam)
{
if (lock)
return 1;
lock = 1;
/* code goes here */
lock = 0;
return 0;
}
When testing with the following:
for (i = 0; i < 2; i++)
thandle[i] = CreateThread(NULL, 0, ThreadProc, NULL, 0, &tid[i]);
WaitForMultipleObjects(2, thandle, TRUE, INFINITE);
I always get the desired effect that only the first thread to be created actually gets to the code and returns 0. However, I keep coming across the suggestion that this method may fail because the lock is not implemented using atomic operations.
I cannot see a way of creating the threads simultaneously, so, in practical terms, is atomicity really needed here? Can someone provide an example that would cause the above to fail?
Aucun commentaire:
Enregistrer un commentaire