Nope, this won't work.
That's because lock++ and lock-- are a series of machine instructions. In a multithreaded program, you can be interrupted at any machine instruction. Therefore, one thread could get the lock value and get interupted before the ++ was applied and the value returned to the variable. That makes another thread able to get the sam lock value. That's your race condition.
What you need is a function that cannot be interupted. These functions are provided by the operating system that you are using. What they do is stop the entire operating system except for one thread. Then that thread that do lock++. After that the operating system must be re-enabled to run many threads.
This is called a critical section.
For Windows it looks like:
- CRITICAL_SECTION var;
-
-
InitializeCriticalSectio(&var); //initialize var
-
-
EnterCriticalSection(&var);
-
//All other threads are blocked
-
-
++lock; //set your lock value
-
-
LeaveCriticalSection(&var);
-
-
//the lock value is guaranteed unique
When you are done with var you will need delete the critical section.
This is all covered in Windows via C/C++ by Jeffrey Richter.
If you are not using Windows, then I can't help you but I do know the principle of creating, entering and leaving critical sections still applies.
Lastly, a critical section only applies to a single process. If you need to syunchronize multiple processes, then you need to research using a mutex.