Is there a C++ design pattern that implements a mechanism or mutex that controls the amount of time a thread...












16















I am looking for a way to guarantee that any time a thread locks a specific resource, it is forced to release that resource after a specific period of time (if it has not already released it). Envision a connection where you need to limit the amount of time any specific thread can own that connection for.



I envision this is how it could be used:



{
std::lock_guard<std::TimeLimitedMutex> lock(this->myTimeLimitedMutex, timeout);
try {
// perform some operation with the resource that myTimeLimitedMutex guards.
}
catch (MutexTimeoutException ex) {
// perform cleanup
}
}


I see that there is a timed_mutex that lets the program timeout if a lock cannot be acquired. I need the timeout to occur after the lock is acquired.



There are already some situations where you get a resource that can be taken away unexpectedly. For instance, a tcp sockets -- once a socket connection is made, code on each side needs to handle the case where the other side drops the connection.



I am looking for a pattern that handle types of resources that normally time out on their own, but when they don't, they need to be reset. This does not have to handle every type of resource.










share|improve this question




















  • 5





    AFAIK only the opposite is provided. I believe you need to write your own.

    – NathanOliver
    Feb 8 at 18:43






  • 4





    The tricky part will be deciding how the thread that currently owns the lock will be notified or otherwise realize that it's lock now belongs to someone else.

    – François Andrieux
    Feb 8 at 18:53






  • 4





    Isn't that a bit against the principle of "owning" a resource? Also, implementing a timeout when you have a lock might get awful in some cases performance-wise. Imagine a timeout of of 500ms but it would have took 505ms to complete all the work. What happens then?

    – AlexG
    Feb 8 at 18:54








  • 4





    This sounds tricky. It may be that you will have to put regular checks in the worker thread whether or not to terminate. I mean what if you only partially modified the state of the resource leaving it in an unpredictable condition for the preempting thread to take over from?

    – Galik
    Feb 8 at 18:59








  • 4





    The thread that owns the lock periodically checks to see how long it has held the lock, and if it exceeds the threshold it relinquishes the lock and does whatever cleanup required. The concept is similar to cooperative multitasking, in contrast to the much more prevalent preemptive multitasking. Note: there's a reason preemptive multitasking is more prevalent, even though it is less efficient than cooperative multitasking.

    – Eljay
    Feb 8 at 20:03
















16















I am looking for a way to guarantee that any time a thread locks a specific resource, it is forced to release that resource after a specific period of time (if it has not already released it). Envision a connection where you need to limit the amount of time any specific thread can own that connection for.



I envision this is how it could be used:



{
std::lock_guard<std::TimeLimitedMutex> lock(this->myTimeLimitedMutex, timeout);
try {
// perform some operation with the resource that myTimeLimitedMutex guards.
}
catch (MutexTimeoutException ex) {
// perform cleanup
}
}


I see that there is a timed_mutex that lets the program timeout if a lock cannot be acquired. I need the timeout to occur after the lock is acquired.



There are already some situations where you get a resource that can be taken away unexpectedly. For instance, a tcp sockets -- once a socket connection is made, code on each side needs to handle the case where the other side drops the connection.



I am looking for a pattern that handle types of resources that normally time out on their own, but when they don't, they need to be reset. This does not have to handle every type of resource.










share|improve this question




















  • 5





    AFAIK only the opposite is provided. I believe you need to write your own.

    – NathanOliver
    Feb 8 at 18:43






  • 4





    The tricky part will be deciding how the thread that currently owns the lock will be notified or otherwise realize that it's lock now belongs to someone else.

    – François Andrieux
    Feb 8 at 18:53






  • 4





    Isn't that a bit against the principle of "owning" a resource? Also, implementing a timeout when you have a lock might get awful in some cases performance-wise. Imagine a timeout of of 500ms but it would have took 505ms to complete all the work. What happens then?

    – AlexG
    Feb 8 at 18:54








  • 4





    This sounds tricky. It may be that you will have to put regular checks in the worker thread whether or not to terminate. I mean what if you only partially modified the state of the resource leaving it in an unpredictable condition for the preempting thread to take over from?

    – Galik
    Feb 8 at 18:59








  • 4





    The thread that owns the lock periodically checks to see how long it has held the lock, and if it exceeds the threshold it relinquishes the lock and does whatever cleanup required. The concept is similar to cooperative multitasking, in contrast to the much more prevalent preemptive multitasking. Note: there's a reason preemptive multitasking is more prevalent, even though it is less efficient than cooperative multitasking.

    – Eljay
    Feb 8 at 20:03














16












16








16


2






I am looking for a way to guarantee that any time a thread locks a specific resource, it is forced to release that resource after a specific period of time (if it has not already released it). Envision a connection where you need to limit the amount of time any specific thread can own that connection for.



I envision this is how it could be used:



{
std::lock_guard<std::TimeLimitedMutex> lock(this->myTimeLimitedMutex, timeout);
try {
// perform some operation with the resource that myTimeLimitedMutex guards.
}
catch (MutexTimeoutException ex) {
// perform cleanup
}
}


I see that there is a timed_mutex that lets the program timeout if a lock cannot be acquired. I need the timeout to occur after the lock is acquired.



There are already some situations where you get a resource that can be taken away unexpectedly. For instance, a tcp sockets -- once a socket connection is made, code on each side needs to handle the case where the other side drops the connection.



I am looking for a pattern that handle types of resources that normally time out on their own, but when they don't, they need to be reset. This does not have to handle every type of resource.










share|improve this question
















I am looking for a way to guarantee that any time a thread locks a specific resource, it is forced to release that resource after a specific period of time (if it has not already released it). Envision a connection where you need to limit the amount of time any specific thread can own that connection for.



I envision this is how it could be used:



{
std::lock_guard<std::TimeLimitedMutex> lock(this->myTimeLimitedMutex, timeout);
try {
// perform some operation with the resource that myTimeLimitedMutex guards.
}
catch (MutexTimeoutException ex) {
// perform cleanup
}
}


I see that there is a timed_mutex that lets the program timeout if a lock cannot be acquired. I need the timeout to occur after the lock is acquired.



There are already some situations where you get a resource that can be taken away unexpectedly. For instance, a tcp sockets -- once a socket connection is made, code on each side needs to handle the case where the other side drops the connection.



I am looking for a pattern that handle types of resources that normally time out on their own, but when they don't, they need to be reset. This does not have to handle every type of resource.







c++ mutex deadlock






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Feb 10 at 17:27







Jay Elston

















asked Feb 8 at 18:42









Jay ElstonJay Elston

1,54011536




1,54011536








  • 5





    AFAIK only the opposite is provided. I believe you need to write your own.

    – NathanOliver
    Feb 8 at 18:43






  • 4





    The tricky part will be deciding how the thread that currently owns the lock will be notified or otherwise realize that it's lock now belongs to someone else.

    – François Andrieux
    Feb 8 at 18:53






  • 4





    Isn't that a bit against the principle of "owning" a resource? Also, implementing a timeout when you have a lock might get awful in some cases performance-wise. Imagine a timeout of of 500ms but it would have took 505ms to complete all the work. What happens then?

    – AlexG
    Feb 8 at 18:54








  • 4





    This sounds tricky. It may be that you will have to put regular checks in the worker thread whether or not to terminate. I mean what if you only partially modified the state of the resource leaving it in an unpredictable condition for the preempting thread to take over from?

    – Galik
    Feb 8 at 18:59








  • 4





    The thread that owns the lock periodically checks to see how long it has held the lock, and if it exceeds the threshold it relinquishes the lock and does whatever cleanup required. The concept is similar to cooperative multitasking, in contrast to the much more prevalent preemptive multitasking. Note: there's a reason preemptive multitasking is more prevalent, even though it is less efficient than cooperative multitasking.

    – Eljay
    Feb 8 at 20:03














  • 5





    AFAIK only the opposite is provided. I believe you need to write your own.

    – NathanOliver
    Feb 8 at 18:43






  • 4





    The tricky part will be deciding how the thread that currently owns the lock will be notified or otherwise realize that it's lock now belongs to someone else.

    – François Andrieux
    Feb 8 at 18:53






  • 4





    Isn't that a bit against the principle of "owning" a resource? Also, implementing a timeout when you have a lock might get awful in some cases performance-wise. Imagine a timeout of of 500ms but it would have took 505ms to complete all the work. What happens then?

    – AlexG
    Feb 8 at 18:54








  • 4





    This sounds tricky. It may be that you will have to put regular checks in the worker thread whether or not to terminate. I mean what if you only partially modified the state of the resource leaving it in an unpredictable condition for the preempting thread to take over from?

    – Galik
    Feb 8 at 18:59








  • 4





    The thread that owns the lock periodically checks to see how long it has held the lock, and if it exceeds the threshold it relinquishes the lock and does whatever cleanup required. The concept is similar to cooperative multitasking, in contrast to the much more prevalent preemptive multitasking. Note: there's a reason preemptive multitasking is more prevalent, even though it is less efficient than cooperative multitasking.

    – Eljay
    Feb 8 at 20:03








5




5





AFAIK only the opposite is provided. I believe you need to write your own.

– NathanOliver
Feb 8 at 18:43





AFAIK only the opposite is provided. I believe you need to write your own.

– NathanOliver
Feb 8 at 18:43




4




4





The tricky part will be deciding how the thread that currently owns the lock will be notified or otherwise realize that it's lock now belongs to someone else.

– François Andrieux
Feb 8 at 18:53





The tricky part will be deciding how the thread that currently owns the lock will be notified or otherwise realize that it's lock now belongs to someone else.

– François Andrieux
Feb 8 at 18:53




4




4





Isn't that a bit against the principle of "owning" a resource? Also, implementing a timeout when you have a lock might get awful in some cases performance-wise. Imagine a timeout of of 500ms but it would have took 505ms to complete all the work. What happens then?

– AlexG
Feb 8 at 18:54







Isn't that a bit against the principle of "owning" a resource? Also, implementing a timeout when you have a lock might get awful in some cases performance-wise. Imagine a timeout of of 500ms but it would have took 505ms to complete all the work. What happens then?

– AlexG
Feb 8 at 18:54






4




4





This sounds tricky. It may be that you will have to put regular checks in the worker thread whether or not to terminate. I mean what if you only partially modified the state of the resource leaving it in an unpredictable condition for the preempting thread to take over from?

– Galik
Feb 8 at 18:59







This sounds tricky. It may be that you will have to put regular checks in the worker thread whether or not to terminate. I mean what if you only partially modified the state of the resource leaving it in an unpredictable condition for the preempting thread to take over from?

– Galik
Feb 8 at 18:59






4




4





The thread that owns the lock periodically checks to see how long it has held the lock, and if it exceeds the threshold it relinquishes the lock and does whatever cleanup required. The concept is similar to cooperative multitasking, in contrast to the much more prevalent preemptive multitasking. Note: there's a reason preemptive multitasking is more prevalent, even though it is less efficient than cooperative multitasking.

– Eljay
Feb 8 at 20:03





The thread that owns the lock periodically checks to see how long it has held the lock, and if it exceeds the threshold it relinquishes the lock and does whatever cleanup required. The concept is similar to cooperative multitasking, in contrast to the much more prevalent preemptive multitasking. Note: there's a reason preemptive multitasking is more prevalent, even though it is less efficient than cooperative multitasking.

– Eljay
Feb 8 at 20:03












5 Answers
5






active

oldest

votes


















33














This can't work, and it will never work. In other words, this can never be made. It goes against all concept of ownership and atomic transactions. Because when thread acquires the lock and implements two transactions in a row, it expects them to become atomically visible to outside word. In this scenario, it would be very possible that the transaction will be torn - first part of it will be performed, but the second will be not.



What's worse is that since the lock will be forcefully removed, the part-executed transaction will become visible to outside word, before the interrupted thread has any chance to roll-back.



This idea goes contrary to all school of multi-threaded thinking.






share|improve this answer



















  • 5





    Some mechanisms for updating shared resources, such as compare-and-swap, can handle "rollbacks" without the interrupted thread having to do anything. Using locks for arbitration may offer better performance than having threads attempt updates which end up failing, but forcibly stealing an object from the thread that's updating it would merely hurt performance, not correctness.

    – supercat
    Feb 8 at 23:39











  • Sergey -- this pattern does not have to work for every resource, and it should be able to work for certain types of resources. That is all that is needed for any design pattern -- that it work in the types of situations it is applicable for.

    – Jay Elston
    Feb 10 at 17:30



















15














I support SergeyAs answer. Releasing a locked mutex after a timeout is a bad idea and cannot work. Mutex stands for mutual exclusion and this is a rock-hard contract which cannot be violated.



But you can do what you want:



Problem: You want to guarantee that your threads do not hold the mutex longer than a certain time T.



Solution: Never lock the mutex for longer than time T. Instead write your code so that the mutex is locked only for the absolutely necessary operations. It is always possible to give such a time T (modulo the uncertainties and limits given my a multitasking and multiuser operating system of course).



To achieve that (examples):




  • Never do file I/O inside a locked section.

  • Never call a system call while a mutex is locked.

  • Avoid sorting a list while a mutex is locked (*).

  • Avoid doing a slow operation on each element of a list while a mutex is locked (*).

  • Avoid memory allocation/deallocation while a mutex is locked (*).


There are exceptions to these rules, but the general guideline is:




  • Make your code slightly less optimal (e.g. do some redundant copying inside the critical section) to make the critical section as short as possible. This is good multithreading programming.


(*) These are just examples for operations where it is tempting to lock the entire list, do the operations and then unlock the list. Instead it is advisable to just take a local copy of the list and clear the original list while the mutex is locked, ideally by using the swap() operation offered by most STL containers. And then do the slow operation on the local copy outside of the critical section. This is not always possible but always worth considering. Sorting has square complexity in the worst case and usually needs random access to the entire list. It is useful to sort (a copy of) the list outside of the critical section and later check whether elements need to be added or removed. Memory allocations also have quite some complexity behind them, so massive memory allocations/deallocations should be avoided.






share|improve this answer


























  • I'm surprised by the "never sort a list" example. Why would that have any less of a time guarantee than any list operation/loop?

    – Mees de Vries
    Feb 9 at 18:16






  • 1





    It is the weakest example in the list I admit. Sorting has square complexity when considering worst cases of useful algorithms like quicksort. And it usually requires you to lock the entire list, since for example quicksort does random accesses. It is advisable to do that outside of the critical section. Of course if you know in advance that you will just a limited amount of elements like 100 integer-like things then this is ok to do that in the critical section. I reworded that less harshly from never to avoid, since I agree, it sounded to harsh.

    – Johannes Overmann
    Feb 9 at 20:20



















5














You can't do that with only C++.



If you are using a Posix system, it can be done.
You'll have to trigger a SIGALARM signal that's only unmasked for the thread that'll timeout. In the signal handler, you'll have to set a flag and use longjmp to return to the thread code.
In the thread code, on the setjmp position, you can only be called if the signal was triggered, thus you can throw the Timeout exception.



Please see this answer for how to do that.



Also, on linux, it seems you can directly throw from the signal handler (so no longjmp/setjmp here).



BTW, if I were you, I would code the opposite. Think about it: You want to tell a thread "hey, you're taking too long, so let's throw away all the (long) work you've done so far so I can make progress".
Ideally, you should have your long thread be more cooperative, doing something like "I've done A of a ABCD task, let's release the mutex so other can progress on A. Then let's check if I can take it again to do B and so on."
You probably want to be more fine grained (have more mutex on smaller objects, but make sure you're locking in the same order) or use RW locks (so that other threads can use the objects if you're not modifying them), etc...






share|improve this answer

































    1














    Such an approach cannot be enforced because the holder of the mutex needs the opportunity to clean up anything which is left in an invalid state part way through the transaction. This can take an unknown arbitrary amount of time.



    The typical approach is to release the lock when doing long tasks, and re-aquire it as needed. You have to manage this yourself as everyone will have a slightly different approach.



    The only situation I know of where this sort of thing is accepted practice is at the kernel level, especially with respect to microcontrollers (which either have no kernel, or are all kernel, depending on who you ask). You can set an interrupt which modifies the call stack, so that when it is triggered it unwinds the particular operations you are interested in.






    share|improve this answer
























    • This pattern would let the application clean things up in the exception handler. The mutex would be locked until the lock_guard gets deleted.

      – Jay Elston
      Feb 10 at 17:33











    • @jayelston if someone wraps the try/catch in a while loop, they can hold the resource indefinitely. This was actually a problem C# with domains. You can forcefully terminate a domain. When you do so, it repeatedly starts throwing exceptions on all threads, trying to break free of such loops. It's actually dependent on a race case to guarantee the threads stop eventually.

      – Cort Ammon
      Feb 10 at 19:16



















    0














    "Condition" variables can have timeouts. This allows you to wait until a thread voluntarily releases a resource (with notify_one() or notify_all()), but the wait itself will timeout after a specified fixed amount of time.



    Examples in the Boost documentation for "conditions" might make this more clear.



    If you want to force a release, you have to write the code which will force it though. This could be dangerous. The code written in C++ can be doing some pretty close-to-the-metal stuff. The resource could be accessing real hardware and it could be waiting on it to finish something. It may not be physically possible to end whatever the program is stuck on.



    However, if it is possible, then you can handle it in the thread in which the wait() times out.






    share|improve this answer
























    • Nope. notify_all() and notify_one() do not release any mutex. And condition variable have no timeout for releasing the mutex.

      – Johannes Overmann
      Feb 9 at 20:22











    • @JohannesOvermann no, there is no timeout for releasing a mutex, the timeout is for waiting on a predicate with wait_for and wait_until. But notify does allow a waiting thread to gain a mutex. I did say that what the OP is asking for (precisely) is not possible. But the effect they want is accomplished with a combination of a wait_*(with a timeout) and a notify. Rather than be pedantic, I tried to be informative.

      – Dmitry Rubanovich
      Feb 10 at 6:17











    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54598455%2fis-there-a-c-design-pattern-that-implements-a-mechanism-or-mutex-that-controls%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    5 Answers
    5






    active

    oldest

    votes








    5 Answers
    5






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    33














    This can't work, and it will never work. In other words, this can never be made. It goes against all concept of ownership and atomic transactions. Because when thread acquires the lock and implements two transactions in a row, it expects them to become atomically visible to outside word. In this scenario, it would be very possible that the transaction will be torn - first part of it will be performed, but the second will be not.



    What's worse is that since the lock will be forcefully removed, the part-executed transaction will become visible to outside word, before the interrupted thread has any chance to roll-back.



    This idea goes contrary to all school of multi-threaded thinking.






    share|improve this answer



















    • 5





      Some mechanisms for updating shared resources, such as compare-and-swap, can handle "rollbacks" without the interrupted thread having to do anything. Using locks for arbitration may offer better performance than having threads attempt updates which end up failing, but forcibly stealing an object from the thread that's updating it would merely hurt performance, not correctness.

      – supercat
      Feb 8 at 23:39











    • Sergey -- this pattern does not have to work for every resource, and it should be able to work for certain types of resources. That is all that is needed for any design pattern -- that it work in the types of situations it is applicable for.

      – Jay Elston
      Feb 10 at 17:30
















    33














    This can't work, and it will never work. In other words, this can never be made. It goes against all concept of ownership and atomic transactions. Because when thread acquires the lock and implements two transactions in a row, it expects them to become atomically visible to outside word. In this scenario, it would be very possible that the transaction will be torn - first part of it will be performed, but the second will be not.



    What's worse is that since the lock will be forcefully removed, the part-executed transaction will become visible to outside word, before the interrupted thread has any chance to roll-back.



    This idea goes contrary to all school of multi-threaded thinking.






    share|improve this answer



















    • 5





      Some mechanisms for updating shared resources, such as compare-and-swap, can handle "rollbacks" without the interrupted thread having to do anything. Using locks for arbitration may offer better performance than having threads attempt updates which end up failing, but forcibly stealing an object from the thread that's updating it would merely hurt performance, not correctness.

      – supercat
      Feb 8 at 23:39











    • Sergey -- this pattern does not have to work for every resource, and it should be able to work for certain types of resources. That is all that is needed for any design pattern -- that it work in the types of situations it is applicable for.

      – Jay Elston
      Feb 10 at 17:30














    33












    33








    33







    This can't work, and it will never work. In other words, this can never be made. It goes against all concept of ownership and atomic transactions. Because when thread acquires the lock and implements two transactions in a row, it expects them to become atomically visible to outside word. In this scenario, it would be very possible that the transaction will be torn - first part of it will be performed, but the second will be not.



    What's worse is that since the lock will be forcefully removed, the part-executed transaction will become visible to outside word, before the interrupted thread has any chance to roll-back.



    This idea goes contrary to all school of multi-threaded thinking.






    share|improve this answer













    This can't work, and it will never work. In other words, this can never be made. It goes against all concept of ownership and atomic transactions. Because when thread acquires the lock and implements two transactions in a row, it expects them to become atomically visible to outside word. In this scenario, it would be very possible that the transaction will be torn - first part of it will be performed, but the second will be not.



    What's worse is that since the lock will be forcefully removed, the part-executed transaction will become visible to outside word, before the interrupted thread has any chance to roll-back.



    This idea goes contrary to all school of multi-threaded thinking.







    share|improve this answer












    share|improve this answer



    share|improve this answer










    answered Feb 8 at 19:01









    SergeyASergeyA

    44k53987




    44k53987








    • 5





      Some mechanisms for updating shared resources, such as compare-and-swap, can handle "rollbacks" without the interrupted thread having to do anything. Using locks for arbitration may offer better performance than having threads attempt updates which end up failing, but forcibly stealing an object from the thread that's updating it would merely hurt performance, not correctness.

      – supercat
      Feb 8 at 23:39











    • Sergey -- this pattern does not have to work for every resource, and it should be able to work for certain types of resources. That is all that is needed for any design pattern -- that it work in the types of situations it is applicable for.

      – Jay Elston
      Feb 10 at 17:30














    • 5





      Some mechanisms for updating shared resources, such as compare-and-swap, can handle "rollbacks" without the interrupted thread having to do anything. Using locks for arbitration may offer better performance than having threads attempt updates which end up failing, but forcibly stealing an object from the thread that's updating it would merely hurt performance, not correctness.

      – supercat
      Feb 8 at 23:39











    • Sergey -- this pattern does not have to work for every resource, and it should be able to work for certain types of resources. That is all that is needed for any design pattern -- that it work in the types of situations it is applicable for.

      – Jay Elston
      Feb 10 at 17:30








    5




    5





    Some mechanisms for updating shared resources, such as compare-and-swap, can handle "rollbacks" without the interrupted thread having to do anything. Using locks for arbitration may offer better performance than having threads attempt updates which end up failing, but forcibly stealing an object from the thread that's updating it would merely hurt performance, not correctness.

    – supercat
    Feb 8 at 23:39





    Some mechanisms for updating shared resources, such as compare-and-swap, can handle "rollbacks" without the interrupted thread having to do anything. Using locks for arbitration may offer better performance than having threads attempt updates which end up failing, but forcibly stealing an object from the thread that's updating it would merely hurt performance, not correctness.

    – supercat
    Feb 8 at 23:39













    Sergey -- this pattern does not have to work for every resource, and it should be able to work for certain types of resources. That is all that is needed for any design pattern -- that it work in the types of situations it is applicable for.

    – Jay Elston
    Feb 10 at 17:30





    Sergey -- this pattern does not have to work for every resource, and it should be able to work for certain types of resources. That is all that is needed for any design pattern -- that it work in the types of situations it is applicable for.

    – Jay Elston
    Feb 10 at 17:30













    15














    I support SergeyAs answer. Releasing a locked mutex after a timeout is a bad idea and cannot work. Mutex stands for mutual exclusion and this is a rock-hard contract which cannot be violated.



    But you can do what you want:



    Problem: You want to guarantee that your threads do not hold the mutex longer than a certain time T.



    Solution: Never lock the mutex for longer than time T. Instead write your code so that the mutex is locked only for the absolutely necessary operations. It is always possible to give such a time T (modulo the uncertainties and limits given my a multitasking and multiuser operating system of course).



    To achieve that (examples):




    • Never do file I/O inside a locked section.

    • Never call a system call while a mutex is locked.

    • Avoid sorting a list while a mutex is locked (*).

    • Avoid doing a slow operation on each element of a list while a mutex is locked (*).

    • Avoid memory allocation/deallocation while a mutex is locked (*).


    There are exceptions to these rules, but the general guideline is:




    • Make your code slightly less optimal (e.g. do some redundant copying inside the critical section) to make the critical section as short as possible. This is good multithreading programming.


    (*) These are just examples for operations where it is tempting to lock the entire list, do the operations and then unlock the list. Instead it is advisable to just take a local copy of the list and clear the original list while the mutex is locked, ideally by using the swap() operation offered by most STL containers. And then do the slow operation on the local copy outside of the critical section. This is not always possible but always worth considering. Sorting has square complexity in the worst case and usually needs random access to the entire list. It is useful to sort (a copy of) the list outside of the critical section and later check whether elements need to be added or removed. Memory allocations also have quite some complexity behind them, so massive memory allocations/deallocations should be avoided.






    share|improve this answer


























    • I'm surprised by the "never sort a list" example. Why would that have any less of a time guarantee than any list operation/loop?

      – Mees de Vries
      Feb 9 at 18:16






    • 1





      It is the weakest example in the list I admit. Sorting has square complexity when considering worst cases of useful algorithms like quicksort. And it usually requires you to lock the entire list, since for example quicksort does random accesses. It is advisable to do that outside of the critical section. Of course if you know in advance that you will just a limited amount of elements like 100 integer-like things then this is ok to do that in the critical section. I reworded that less harshly from never to avoid, since I agree, it sounded to harsh.

      – Johannes Overmann
      Feb 9 at 20:20
















    15














    I support SergeyAs answer. Releasing a locked mutex after a timeout is a bad idea and cannot work. Mutex stands for mutual exclusion and this is a rock-hard contract which cannot be violated.



    But you can do what you want:



    Problem: You want to guarantee that your threads do not hold the mutex longer than a certain time T.



    Solution: Never lock the mutex for longer than time T. Instead write your code so that the mutex is locked only for the absolutely necessary operations. It is always possible to give such a time T (modulo the uncertainties and limits given my a multitasking and multiuser operating system of course).



    To achieve that (examples):




    • Never do file I/O inside a locked section.

    • Never call a system call while a mutex is locked.

    • Avoid sorting a list while a mutex is locked (*).

    • Avoid doing a slow operation on each element of a list while a mutex is locked (*).

    • Avoid memory allocation/deallocation while a mutex is locked (*).


    There are exceptions to these rules, but the general guideline is:




    • Make your code slightly less optimal (e.g. do some redundant copying inside the critical section) to make the critical section as short as possible. This is good multithreading programming.


    (*) These are just examples for operations where it is tempting to lock the entire list, do the operations and then unlock the list. Instead it is advisable to just take a local copy of the list and clear the original list while the mutex is locked, ideally by using the swap() operation offered by most STL containers. And then do the slow operation on the local copy outside of the critical section. This is not always possible but always worth considering. Sorting has square complexity in the worst case and usually needs random access to the entire list. It is useful to sort (a copy of) the list outside of the critical section and later check whether elements need to be added or removed. Memory allocations also have quite some complexity behind them, so massive memory allocations/deallocations should be avoided.






    share|improve this answer


























    • I'm surprised by the "never sort a list" example. Why would that have any less of a time guarantee than any list operation/loop?

      – Mees de Vries
      Feb 9 at 18:16






    • 1





      It is the weakest example in the list I admit. Sorting has square complexity when considering worst cases of useful algorithms like quicksort. And it usually requires you to lock the entire list, since for example quicksort does random accesses. It is advisable to do that outside of the critical section. Of course if you know in advance that you will just a limited amount of elements like 100 integer-like things then this is ok to do that in the critical section. I reworded that less harshly from never to avoid, since I agree, it sounded to harsh.

      – Johannes Overmann
      Feb 9 at 20:20














    15












    15








    15







    I support SergeyAs answer. Releasing a locked mutex after a timeout is a bad idea and cannot work. Mutex stands for mutual exclusion and this is a rock-hard contract which cannot be violated.



    But you can do what you want:



    Problem: You want to guarantee that your threads do not hold the mutex longer than a certain time T.



    Solution: Never lock the mutex for longer than time T. Instead write your code so that the mutex is locked only for the absolutely necessary operations. It is always possible to give such a time T (modulo the uncertainties and limits given my a multitasking and multiuser operating system of course).



    To achieve that (examples):




    • Never do file I/O inside a locked section.

    • Never call a system call while a mutex is locked.

    • Avoid sorting a list while a mutex is locked (*).

    • Avoid doing a slow operation on each element of a list while a mutex is locked (*).

    • Avoid memory allocation/deallocation while a mutex is locked (*).


    There are exceptions to these rules, but the general guideline is:




    • Make your code slightly less optimal (e.g. do some redundant copying inside the critical section) to make the critical section as short as possible. This is good multithreading programming.


    (*) These are just examples for operations where it is tempting to lock the entire list, do the operations and then unlock the list. Instead it is advisable to just take a local copy of the list and clear the original list while the mutex is locked, ideally by using the swap() operation offered by most STL containers. And then do the slow operation on the local copy outside of the critical section. This is not always possible but always worth considering. Sorting has square complexity in the worst case and usually needs random access to the entire list. It is useful to sort (a copy of) the list outside of the critical section and later check whether elements need to be added or removed. Memory allocations also have quite some complexity behind them, so massive memory allocations/deallocations should be avoided.






    share|improve this answer















    I support SergeyAs answer. Releasing a locked mutex after a timeout is a bad idea and cannot work. Mutex stands for mutual exclusion and this is a rock-hard contract which cannot be violated.



    But you can do what you want:



    Problem: You want to guarantee that your threads do not hold the mutex longer than a certain time T.



    Solution: Never lock the mutex for longer than time T. Instead write your code so that the mutex is locked only for the absolutely necessary operations. It is always possible to give such a time T (modulo the uncertainties and limits given my a multitasking and multiuser operating system of course).



    To achieve that (examples):




    • Never do file I/O inside a locked section.

    • Never call a system call while a mutex is locked.

    • Avoid sorting a list while a mutex is locked (*).

    • Avoid doing a slow operation on each element of a list while a mutex is locked (*).

    • Avoid memory allocation/deallocation while a mutex is locked (*).


    There are exceptions to these rules, but the general guideline is:




    • Make your code slightly less optimal (e.g. do some redundant copying inside the critical section) to make the critical section as short as possible. This is good multithreading programming.


    (*) These are just examples for operations where it is tempting to lock the entire list, do the operations and then unlock the list. Instead it is advisable to just take a local copy of the list and clear the original list while the mutex is locked, ideally by using the swap() operation offered by most STL containers. And then do the slow operation on the local copy outside of the critical section. This is not always possible but always worth considering. Sorting has square complexity in the worst case and usually needs random access to the entire list. It is useful to sort (a copy of) the list outside of the critical section and later check whether elements need to be added or removed. Memory allocations also have quite some complexity behind them, so massive memory allocations/deallocations should be avoided.







    share|improve this answer














    share|improve this answer



    share|improve this answer








    edited Feb 12 at 11:36

























    answered Feb 8 at 19:24









    Johannes OvermannJohannes Overmann

    3,7951325




    3,7951325













    • I'm surprised by the "never sort a list" example. Why would that have any less of a time guarantee than any list operation/loop?

      – Mees de Vries
      Feb 9 at 18:16






    • 1





      It is the weakest example in the list I admit. Sorting has square complexity when considering worst cases of useful algorithms like quicksort. And it usually requires you to lock the entire list, since for example quicksort does random accesses. It is advisable to do that outside of the critical section. Of course if you know in advance that you will just a limited amount of elements like 100 integer-like things then this is ok to do that in the critical section. I reworded that less harshly from never to avoid, since I agree, it sounded to harsh.

      – Johannes Overmann
      Feb 9 at 20:20



















    • I'm surprised by the "never sort a list" example. Why would that have any less of a time guarantee than any list operation/loop?

      – Mees de Vries
      Feb 9 at 18:16






    • 1





      It is the weakest example in the list I admit. Sorting has square complexity when considering worst cases of useful algorithms like quicksort. And it usually requires you to lock the entire list, since for example quicksort does random accesses. It is advisable to do that outside of the critical section. Of course if you know in advance that you will just a limited amount of elements like 100 integer-like things then this is ok to do that in the critical section. I reworded that less harshly from never to avoid, since I agree, it sounded to harsh.

      – Johannes Overmann
      Feb 9 at 20:20

















    I'm surprised by the "never sort a list" example. Why would that have any less of a time guarantee than any list operation/loop?

    – Mees de Vries
    Feb 9 at 18:16





    I'm surprised by the "never sort a list" example. Why would that have any less of a time guarantee than any list operation/loop?

    – Mees de Vries
    Feb 9 at 18:16




    1




    1





    It is the weakest example in the list I admit. Sorting has square complexity when considering worst cases of useful algorithms like quicksort. And it usually requires you to lock the entire list, since for example quicksort does random accesses. It is advisable to do that outside of the critical section. Of course if you know in advance that you will just a limited amount of elements like 100 integer-like things then this is ok to do that in the critical section. I reworded that less harshly from never to avoid, since I agree, it sounded to harsh.

    – Johannes Overmann
    Feb 9 at 20:20





    It is the weakest example in the list I admit. Sorting has square complexity when considering worst cases of useful algorithms like quicksort. And it usually requires you to lock the entire list, since for example quicksort does random accesses. It is advisable to do that outside of the critical section. Of course if you know in advance that you will just a limited amount of elements like 100 integer-like things then this is ok to do that in the critical section. I reworded that less harshly from never to avoid, since I agree, it sounded to harsh.

    – Johannes Overmann
    Feb 9 at 20:20











    5














    You can't do that with only C++.



    If you are using a Posix system, it can be done.
    You'll have to trigger a SIGALARM signal that's only unmasked for the thread that'll timeout. In the signal handler, you'll have to set a flag and use longjmp to return to the thread code.
    In the thread code, on the setjmp position, you can only be called if the signal was triggered, thus you can throw the Timeout exception.



    Please see this answer for how to do that.



    Also, on linux, it seems you can directly throw from the signal handler (so no longjmp/setjmp here).



    BTW, if I were you, I would code the opposite. Think about it: You want to tell a thread "hey, you're taking too long, so let's throw away all the (long) work you've done so far so I can make progress".
    Ideally, you should have your long thread be more cooperative, doing something like "I've done A of a ABCD task, let's release the mutex so other can progress on A. Then let's check if I can take it again to do B and so on."
    You probably want to be more fine grained (have more mutex on smaller objects, but make sure you're locking in the same order) or use RW locks (so that other threads can use the objects if you're not modifying them), etc...






    share|improve this answer






























      5














      You can't do that with only C++.



      If you are using a Posix system, it can be done.
      You'll have to trigger a SIGALARM signal that's only unmasked for the thread that'll timeout. In the signal handler, you'll have to set a flag and use longjmp to return to the thread code.
      In the thread code, on the setjmp position, you can only be called if the signal was triggered, thus you can throw the Timeout exception.



      Please see this answer for how to do that.



      Also, on linux, it seems you can directly throw from the signal handler (so no longjmp/setjmp here).



      BTW, if I were you, I would code the opposite. Think about it: You want to tell a thread "hey, you're taking too long, so let's throw away all the (long) work you've done so far so I can make progress".
      Ideally, you should have your long thread be more cooperative, doing something like "I've done A of a ABCD task, let's release the mutex so other can progress on A. Then let's check if I can take it again to do B and so on."
      You probably want to be more fine grained (have more mutex on smaller objects, but make sure you're locking in the same order) or use RW locks (so that other threads can use the objects if you're not modifying them), etc...






      share|improve this answer




























        5












        5








        5







        You can't do that with only C++.



        If you are using a Posix system, it can be done.
        You'll have to trigger a SIGALARM signal that's only unmasked for the thread that'll timeout. In the signal handler, you'll have to set a flag and use longjmp to return to the thread code.
        In the thread code, on the setjmp position, you can only be called if the signal was triggered, thus you can throw the Timeout exception.



        Please see this answer for how to do that.



        Also, on linux, it seems you can directly throw from the signal handler (so no longjmp/setjmp here).



        BTW, if I were you, I would code the opposite. Think about it: You want to tell a thread "hey, you're taking too long, so let's throw away all the (long) work you've done so far so I can make progress".
        Ideally, you should have your long thread be more cooperative, doing something like "I've done A of a ABCD task, let's release the mutex so other can progress on A. Then let's check if I can take it again to do B and so on."
        You probably want to be more fine grained (have more mutex on smaller objects, but make sure you're locking in the same order) or use RW locks (so that other threads can use the objects if you're not modifying them), etc...






        share|improve this answer















        You can't do that with only C++.



        If you are using a Posix system, it can be done.
        You'll have to trigger a SIGALARM signal that's only unmasked for the thread that'll timeout. In the signal handler, you'll have to set a flag and use longjmp to return to the thread code.
        In the thread code, on the setjmp position, you can only be called if the signal was triggered, thus you can throw the Timeout exception.



        Please see this answer for how to do that.



        Also, on linux, it seems you can directly throw from the signal handler (so no longjmp/setjmp here).



        BTW, if I were you, I would code the opposite. Think about it: You want to tell a thread "hey, you're taking too long, so let's throw away all the (long) work you've done so far so I can make progress".
        Ideally, you should have your long thread be more cooperative, doing something like "I've done A of a ABCD task, let's release the mutex so other can progress on A. Then let's check if I can take it again to do B and so on."
        You probably want to be more fine grained (have more mutex on smaller objects, but make sure you're locking in the same order) or use RW locks (so that other threads can use the objects if you're not modifying them), etc...







        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited Feb 8 at 23:35

























        answered Feb 8 at 23:24









        xryl669xryl669

        1,5291327




        1,5291327























            1














            Such an approach cannot be enforced because the holder of the mutex needs the opportunity to clean up anything which is left in an invalid state part way through the transaction. This can take an unknown arbitrary amount of time.



            The typical approach is to release the lock when doing long tasks, and re-aquire it as needed. You have to manage this yourself as everyone will have a slightly different approach.



            The only situation I know of where this sort of thing is accepted practice is at the kernel level, especially with respect to microcontrollers (which either have no kernel, or are all kernel, depending on who you ask). You can set an interrupt which modifies the call stack, so that when it is triggered it unwinds the particular operations you are interested in.






            share|improve this answer
























            • This pattern would let the application clean things up in the exception handler. The mutex would be locked until the lock_guard gets deleted.

              – Jay Elston
              Feb 10 at 17:33











            • @jayelston if someone wraps the try/catch in a while loop, they can hold the resource indefinitely. This was actually a problem C# with domains. You can forcefully terminate a domain. When you do so, it repeatedly starts throwing exceptions on all threads, trying to break free of such loops. It's actually dependent on a race case to guarantee the threads stop eventually.

              – Cort Ammon
              Feb 10 at 19:16
















            1














            Such an approach cannot be enforced because the holder of the mutex needs the opportunity to clean up anything which is left in an invalid state part way through the transaction. This can take an unknown arbitrary amount of time.



            The typical approach is to release the lock when doing long tasks, and re-aquire it as needed. You have to manage this yourself as everyone will have a slightly different approach.



            The only situation I know of where this sort of thing is accepted practice is at the kernel level, especially with respect to microcontrollers (which either have no kernel, or are all kernel, depending on who you ask). You can set an interrupt which modifies the call stack, so that when it is triggered it unwinds the particular operations you are interested in.






            share|improve this answer
























            • This pattern would let the application clean things up in the exception handler. The mutex would be locked until the lock_guard gets deleted.

              – Jay Elston
              Feb 10 at 17:33











            • @jayelston if someone wraps the try/catch in a while loop, they can hold the resource indefinitely. This was actually a problem C# with domains. You can forcefully terminate a domain. When you do so, it repeatedly starts throwing exceptions on all threads, trying to break free of such loops. It's actually dependent on a race case to guarantee the threads stop eventually.

              – Cort Ammon
              Feb 10 at 19:16














            1












            1








            1







            Such an approach cannot be enforced because the holder of the mutex needs the opportunity to clean up anything which is left in an invalid state part way through the transaction. This can take an unknown arbitrary amount of time.



            The typical approach is to release the lock when doing long tasks, and re-aquire it as needed. You have to manage this yourself as everyone will have a slightly different approach.



            The only situation I know of where this sort of thing is accepted practice is at the kernel level, especially with respect to microcontrollers (which either have no kernel, or are all kernel, depending on who you ask). You can set an interrupt which modifies the call stack, so that when it is triggered it unwinds the particular operations you are interested in.






            share|improve this answer













            Such an approach cannot be enforced because the holder of the mutex needs the opportunity to clean up anything which is left in an invalid state part way through the transaction. This can take an unknown arbitrary amount of time.



            The typical approach is to release the lock when doing long tasks, and re-aquire it as needed. You have to manage this yourself as everyone will have a slightly different approach.



            The only situation I know of where this sort of thing is accepted practice is at the kernel level, especially with respect to microcontrollers (which either have no kernel, or are all kernel, depending on who you ask). You can set an interrupt which modifies the call stack, so that when it is triggered it unwinds the particular operations you are interested in.







            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered Feb 8 at 22:56









            Cort AmmonCort Ammon

            5,6271634




            5,6271634













            • This pattern would let the application clean things up in the exception handler. The mutex would be locked until the lock_guard gets deleted.

              – Jay Elston
              Feb 10 at 17:33











            • @jayelston if someone wraps the try/catch in a while loop, they can hold the resource indefinitely. This was actually a problem C# with domains. You can forcefully terminate a domain. When you do so, it repeatedly starts throwing exceptions on all threads, trying to break free of such loops. It's actually dependent on a race case to guarantee the threads stop eventually.

              – Cort Ammon
              Feb 10 at 19:16



















            • This pattern would let the application clean things up in the exception handler. The mutex would be locked until the lock_guard gets deleted.

              – Jay Elston
              Feb 10 at 17:33











            • @jayelston if someone wraps the try/catch in a while loop, they can hold the resource indefinitely. This was actually a problem C# with domains. You can forcefully terminate a domain. When you do so, it repeatedly starts throwing exceptions on all threads, trying to break free of such loops. It's actually dependent on a race case to guarantee the threads stop eventually.

              – Cort Ammon
              Feb 10 at 19:16

















            This pattern would let the application clean things up in the exception handler. The mutex would be locked until the lock_guard gets deleted.

            – Jay Elston
            Feb 10 at 17:33





            This pattern would let the application clean things up in the exception handler. The mutex would be locked until the lock_guard gets deleted.

            – Jay Elston
            Feb 10 at 17:33













            @jayelston if someone wraps the try/catch in a while loop, they can hold the resource indefinitely. This was actually a problem C# with domains. You can forcefully terminate a domain. When you do so, it repeatedly starts throwing exceptions on all threads, trying to break free of such loops. It's actually dependent on a race case to guarantee the threads stop eventually.

            – Cort Ammon
            Feb 10 at 19:16





            @jayelston if someone wraps the try/catch in a while loop, they can hold the resource indefinitely. This was actually a problem C# with domains. You can forcefully terminate a domain. When you do so, it repeatedly starts throwing exceptions on all threads, trying to break free of such loops. It's actually dependent on a race case to guarantee the threads stop eventually.

            – Cort Ammon
            Feb 10 at 19:16











            0














            "Condition" variables can have timeouts. This allows you to wait until a thread voluntarily releases a resource (with notify_one() or notify_all()), but the wait itself will timeout after a specified fixed amount of time.



            Examples in the Boost documentation for "conditions" might make this more clear.



            If you want to force a release, you have to write the code which will force it though. This could be dangerous. The code written in C++ can be doing some pretty close-to-the-metal stuff. The resource could be accessing real hardware and it could be waiting on it to finish something. It may not be physically possible to end whatever the program is stuck on.



            However, if it is possible, then you can handle it in the thread in which the wait() times out.






            share|improve this answer
























            • Nope. notify_all() and notify_one() do not release any mutex. And condition variable have no timeout for releasing the mutex.

              – Johannes Overmann
              Feb 9 at 20:22











            • @JohannesOvermann no, there is no timeout for releasing a mutex, the timeout is for waiting on a predicate with wait_for and wait_until. But notify does allow a waiting thread to gain a mutex. I did say that what the OP is asking for (precisely) is not possible. But the effect they want is accomplished with a combination of a wait_*(with a timeout) and a notify. Rather than be pedantic, I tried to be informative.

              – Dmitry Rubanovich
              Feb 10 at 6:17
















            0














            "Condition" variables can have timeouts. This allows you to wait until a thread voluntarily releases a resource (with notify_one() or notify_all()), but the wait itself will timeout after a specified fixed amount of time.



            Examples in the Boost documentation for "conditions" might make this more clear.



            If you want to force a release, you have to write the code which will force it though. This could be dangerous. The code written in C++ can be doing some pretty close-to-the-metal stuff. The resource could be accessing real hardware and it could be waiting on it to finish something. It may not be physically possible to end whatever the program is stuck on.



            However, if it is possible, then you can handle it in the thread in which the wait() times out.






            share|improve this answer
























            • Nope. notify_all() and notify_one() do not release any mutex. And condition variable have no timeout for releasing the mutex.

              – Johannes Overmann
              Feb 9 at 20:22











            • @JohannesOvermann no, there is no timeout for releasing a mutex, the timeout is for waiting on a predicate with wait_for and wait_until. But notify does allow a waiting thread to gain a mutex. I did say that what the OP is asking for (precisely) is not possible. But the effect they want is accomplished with a combination of a wait_*(with a timeout) and a notify. Rather than be pedantic, I tried to be informative.

              – Dmitry Rubanovich
              Feb 10 at 6:17














            0












            0








            0







            "Condition" variables can have timeouts. This allows you to wait until a thread voluntarily releases a resource (with notify_one() or notify_all()), but the wait itself will timeout after a specified fixed amount of time.



            Examples in the Boost documentation for "conditions" might make this more clear.



            If you want to force a release, you have to write the code which will force it though. This could be dangerous. The code written in C++ can be doing some pretty close-to-the-metal stuff. The resource could be accessing real hardware and it could be waiting on it to finish something. It may not be physically possible to end whatever the program is stuck on.



            However, if it is possible, then you can handle it in the thread in which the wait() times out.






            share|improve this answer













            "Condition" variables can have timeouts. This allows you to wait until a thread voluntarily releases a resource (with notify_one() or notify_all()), but the wait itself will timeout after a specified fixed amount of time.



            Examples in the Boost documentation for "conditions" might make this more clear.



            If you want to force a release, you have to write the code which will force it though. This could be dangerous. The code written in C++ can be doing some pretty close-to-the-metal stuff. The resource could be accessing real hardware and it could be waiting on it to finish something. It may not be physically possible to end whatever the program is stuck on.



            However, if it is possible, then you can handle it in the thread in which the wait() times out.







            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered Feb 9 at 5:32









            Dmitry RubanovichDmitry Rubanovich

            1,9141121




            1,9141121













            • Nope. notify_all() and notify_one() do not release any mutex. And condition variable have no timeout for releasing the mutex.

              – Johannes Overmann
              Feb 9 at 20:22











            • @JohannesOvermann no, there is no timeout for releasing a mutex, the timeout is for waiting on a predicate with wait_for and wait_until. But notify does allow a waiting thread to gain a mutex. I did say that what the OP is asking for (precisely) is not possible. But the effect they want is accomplished with a combination of a wait_*(with a timeout) and a notify. Rather than be pedantic, I tried to be informative.

              – Dmitry Rubanovich
              Feb 10 at 6:17



















            • Nope. notify_all() and notify_one() do not release any mutex. And condition variable have no timeout for releasing the mutex.

              – Johannes Overmann
              Feb 9 at 20:22











            • @JohannesOvermann no, there is no timeout for releasing a mutex, the timeout is for waiting on a predicate with wait_for and wait_until. But notify does allow a waiting thread to gain a mutex. I did say that what the OP is asking for (precisely) is not possible. But the effect they want is accomplished with a combination of a wait_*(with a timeout) and a notify. Rather than be pedantic, I tried to be informative.

              – Dmitry Rubanovich
              Feb 10 at 6:17

















            Nope. notify_all() and notify_one() do not release any mutex. And condition variable have no timeout for releasing the mutex.

            – Johannes Overmann
            Feb 9 at 20:22





            Nope. notify_all() and notify_one() do not release any mutex. And condition variable have no timeout for releasing the mutex.

            – Johannes Overmann
            Feb 9 at 20:22













            @JohannesOvermann no, there is no timeout for releasing a mutex, the timeout is for waiting on a predicate with wait_for and wait_until. But notify does allow a waiting thread to gain a mutex. I did say that what the OP is asking for (precisely) is not possible. But the effect they want is accomplished with a combination of a wait_*(with a timeout) and a notify. Rather than be pedantic, I tried to be informative.

            – Dmitry Rubanovich
            Feb 10 at 6:17





            @JohannesOvermann no, there is no timeout for releasing a mutex, the timeout is for waiting on a predicate with wait_for and wait_until. But notify does allow a waiting thread to gain a mutex. I did say that what the OP is asking for (precisely) is not possible. But the effect they want is accomplished with a combination of a wait_*(with a timeout) and a notify. Rather than be pedantic, I tried to be informative.

            – Dmitry Rubanovich
            Feb 10 at 6:17


















            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54598455%2fis-there-a-c-design-pattern-that-implements-a-mechanism-or-mutex-that-controls%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Probability when a professor distributes a quiz and homework assignment to a class of n students.

            Aardman Animations

            Are they similar matrix