Search the Community
Showing results for tags 'mutex'.
Found 1 result
-
Hello 🙂I have the following code in Delphi12, with slow functions PerformCalculations and SaveDataToDisk: function MutexBarrier(resource_mutex_id :String) :THandle; var Mutex :THandle; begin Mutex:=CreateMutex(nil,false,PChar(resource_mutex_id)); WaitForSingleObject(Mutex,INFINITE); result:=Mutex; end; procedure Main; //process main code (N processes are being run): var mutex :THandle; begin repeat mutex:=MutexBarrier('Mutex1_constant_unique_name'); try Prepare; finally ReleaseMutex(mutex); CloseHandle(mutex); end; PerformCalculations; mutex:=MutexBarrier('Mutex2_constant_unique_name'); try SaveDataToDisk; finally ReleaseMutex(mutex); CloseHandle(mutex); end; until False; end; I'm running N processes with this code, each on separate core (set with affinity, the number of cores > N). Processes do not create additional threads. Processes are run by a separate script like "proc.exe -core=x", where x is the expected affinity. Affinity is set correctly. But the effect of usage of mutexes is strange: 1. Initially all N processes quickly create queue on Mutex1, go through it one after another and then in parallel they are performing calculations on separate cores. 2. Then all N processes start to wait on Mutex2, and one of them (lets name it Process A) gets to the critical section of Mutex2. This is ok. 3. Then the process A which passed critical section of Mutex2 is going through Mutex1 and is performing calculations. At the same time all other processes still wait on Mutex1. - this is strange. 4. Only when process A finishes calculations and enters Mutex2 queue then some other process (name it process B) is entering the critical section of Mutex2. - This is very strange to me. 5. Then process B goes through Mutex1 and performs calculations., etc. In the effect, starting from point 3 only one process is performing calculations at a time. This is very strange to me. Why Mutex2 behaves like that. It is Win10. Remark 1: When SaveDataToDisk is fast (or not called at all - empty critical section of Mutex2), the problem is not happening - and all processes execute PerformCalculations in parallel. Remark 2: I have also verified that Prepare, PerformCalculations and SaveDataToDisk are not failing. I'm searching how to make Mutex2 to behave like expected, but no success till now. Maybe someone has some idea?