Semaphore

Hi
Why semaphore only can be used in task instead of function?
if i want using in function, how should i do? i have two functions running parallel to access a common resource
Thanks

In reply to timag:

Because tasks can potentially consume time (block/suspend), whereas functions cannot. The get() method of a semaphore is a task that can potentially block waiting for a key.

You could use the function try_get() instead. However, you cannot really have two functions running in parallel because they both consume 0 time. One will execute before the other.

In reply to dave_59:
there is try_get() API in semaphore. do u mean that i use it?

In reply to timag:
Either you can use try_get() or you can use fork-join_none in function which gets the key and also you can have the logic after getting a key.

In reply to timag:

It really doesn’t make much sense to use semaphores in functions. Yes you can call try_get() from another function. But what if it returns false, then what do you do? You can’t keep calling it until it returns true because you get into a infinite zero-delay loop.

In reply to dave_59:

for example , i have queue in my code. And I have two class A and B.
there is functionA in classA which put some data to the queue. Another function B is to clean
the queue data. Two functions running paraelly, I worry that when function A is putting some data and functionA is cleaning queue at the same time. therefore i want to ensure function B should clear the queue only for no one accessing this queue.

In reply to timag:

Hello all, Why not simply declaring those pop and push function as tasks? Having a function that does it for you could cause issues due to the 0 delay execution which is dangerous in case of loops. Is there amy restrictions in using function instead of task ?.

Trying to call try_get and try_put i believe could cause some clashes since a 0 delay function could be executed before another in a not known manner i believe. Regards

In reply to timag:

In reply to dave_59:
for example , i have queue in my code. And I have two class A and B.
there is functionA in classA which put some data to the queue. Another function B is to clean
the queue data. Two functions running paraelly, I worry that when function A is putting some data and functionA is cleaning queue at the same time. therefore i want to ensure function B should clear the queue only for no one accessing this queue.

What you’re describing still makes no sense. A and B are functions that do not consume time. The put and the clear are in a race to modify the queue, last modification wins.

But even if you could use a semaphore, the get needs to be able to suspend if the resource is not available. You can’t do that in a function. And if you use try_get() and it fails, you still need to be able to suspend for some amount before you try to call try_get again.