One thread at the time shall pass.

Hello everyone

I have this function what can be called with many thread but
if one thread is already in the function, others must wait until thread
has done doing thing on function.

this was my idea:
1
2
3
4
5
6
7
8
9
bool IsUsingMyFunc = false;
void MyFunc() {
while( IsUsingMyFunc ) Sleep(1);
IsUsingMyFunc = true;
/*
stuff happening between
*/
IsUsingMyFunc = false;
}


I am still little worried that there may be a time when 2 or more threads somehow pass that.

Also i don't think sleeping 1 would be a good idea.
There must be better way to do it.

Thanks
You're asking about a mutex.

As each thread reaches the special code that only one thread at a time should be running, each thread tries to lock the shared mutex.

If they can't lock it, they wait. If they can lock it, they carry on and when they're done, unlock it.

http://www.cplusplus.com/reference/mutex/mutex/
maybe a stupid question but does this work with windows thread?
https://msdn.microsoft.com/en-us/library/windows/desktop/ms682453(v=vs.85).aspx
Yes it does.

However, don't use the windows threading API unless you really have to. Now that C++11 has proper thread support, just use C++ threads.
Last edited on
Topic archived. No new replies allowed.