Sync N processes using semaphore - condition race





.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty{ height:90px;width:728px;box-sizing:border-box;
}







0















I'm trying to order N processes using only semaphores (no mutex).




P1 -> P2 -> P3 -> ... -> Pn




Im dealing with this problem:



if you call:



s = 1;

P1 {
wait(s1)
...
signal(s1)
}

P2 {
wait(s1)
...
signal(s1)
}


How to prevent that it wouldn't start to loop in one proccess? Like the one process that released semaphore wont take it over again? I need all processes to get a turn eventually.



I would also appreciate any suggestions on how to solve this kind of problem (syncing N processes) ONLY using semaphores, without using N semaphores, I read that possible minimum is 3.



Thanks.










share|improve this question

























  • related to stackoverflow.com/q/12685112/537980

    – ctrl-alt-delor
    Nov 25 '18 at 9:28


















0















I'm trying to order N processes using only semaphores (no mutex).




P1 -> P2 -> P3 -> ... -> Pn




Im dealing with this problem:



if you call:



s = 1;

P1 {
wait(s1)
...
signal(s1)
}

P2 {
wait(s1)
...
signal(s1)
}


How to prevent that it wouldn't start to loop in one proccess? Like the one process that released semaphore wont take it over again? I need all processes to get a turn eventually.



I would also appreciate any suggestions on how to solve this kind of problem (syncing N processes) ONLY using semaphores, without using N semaphores, I read that possible minimum is 3.



Thanks.










share|improve this question

























  • related to stackoverflow.com/q/12685112/537980

    – ctrl-alt-delor
    Nov 25 '18 at 9:28














0












0








0








I'm trying to order N processes using only semaphores (no mutex).




P1 -> P2 -> P3 -> ... -> Pn




Im dealing with this problem:



if you call:



s = 1;

P1 {
wait(s1)
...
signal(s1)
}

P2 {
wait(s1)
...
signal(s1)
}


How to prevent that it wouldn't start to loop in one proccess? Like the one process that released semaphore wont take it over again? I need all processes to get a turn eventually.



I would also appreciate any suggestions on how to solve this kind of problem (syncing N processes) ONLY using semaphores, without using N semaphores, I read that possible minimum is 3.



Thanks.










share|improve this question
















I'm trying to order N processes using only semaphores (no mutex).




P1 -> P2 -> P3 -> ... -> Pn




Im dealing with this problem:



if you call:



s = 1;

P1 {
wait(s1)
...
signal(s1)
}

P2 {
wait(s1)
...
signal(s1)
}


How to prevent that it wouldn't start to loop in one proccess? Like the one process that released semaphore wont take it over again? I need all processes to get a turn eventually.



I would also appreciate any suggestions on how to solve this kind of problem (syncing N processes) ONLY using semaphores, without using N semaphores, I read that possible minimum is 3.



Thanks.







multithreading concurrency process operating-system semaphore






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 25 '18 at 9:07









ctrl-alt-delor

4,34732644




4,34732644










asked Nov 24 '18 at 15:40









MiracleMiracle

184




184













  • related to stackoverflow.com/q/12685112/537980

    – ctrl-alt-delor
    Nov 25 '18 at 9:28



















  • related to stackoverflow.com/q/12685112/537980

    – ctrl-alt-delor
    Nov 25 '18 at 9:28

















related to stackoverflow.com/q/12685112/537980

– ctrl-alt-delor
Nov 25 '18 at 9:28





related to stackoverflow.com/q/12685112/537980

– ctrl-alt-delor
Nov 25 '18 at 9:28












1 Answer
1






active

oldest

votes


















0














Here are some options. Because you are always calling signal immediately followed by wait, the co-routine option is probably the best. You have no parallelisable code, so can not benefit from normal threads. It will also be useful to learn about avoiding the need for synchronisation.




  • You can use more than one semaphore. Where each thread, explicitly hands control to the next.


  • You can have a Whose-turn-is-next variable. After getting the lock, a thread will check to see if it is its turn, if not it will free the lock. This could result in spinning, doing nothing. So we would have to add another lock. After checking we would wait on another lock has-somethread-finished. This will be freed after a thread has done some work. Now threads don't spin. However every time a thread finishes, every other thread will check to see if it is next.



The solutions so far while directly answering your question, are anti-patterns. You are just making a multi-threaded program, run single threaded, by using semaphores to fully synchronise the threads.



This one is nether a pattern or anti-pattern, just a note




  • On Unix a thread will eventually get de-scheduled, if it hogs the processor, and there are other threads ready to run.


Better ways to do it.




  • Avoid need for synchronisation:

    (see https://www.youtube.com/watch?v=2yXtZ8x7TXw) If you don't use mutable variables, then concurrency is easy, and there is no need for synchronisation.


  • Consider pipes and filters: in this pattern threads can communicate via a pipe (fifo). You can use a minimal locking circular buffer for this (just ensure that you only put immutable data into the buffer). |In Unixes (such as Gnu/Linux), you can use pipes and processes. You can do this all within one program, using fork. Or you can connect several programs together (bash is a good tool for this).


  • Consider micro-threads / co-routines / co-operative threads:

    Sometimes it is nice to write a program with several independent threads. But if your threads do not spend a significant amount of time running concurrently (for example because you always call signal; wait), then you do not need threads. And threads produce a significant amount of complexity to the code. Therefore use co-routines (or what ever they are called on your system), they allow you to write several routines to be scheduled independently, but control will only be handed over to another co-routine when yield is called (similar to calling signal; wait, but the mechanism will prefer to hand over to the next co-routine in the ring.







share|improve this answer


























    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%2f53459742%2fsync-n-processes-using-semaphore-condition-race%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    0














    Here are some options. Because you are always calling signal immediately followed by wait, the co-routine option is probably the best. You have no parallelisable code, so can not benefit from normal threads. It will also be useful to learn about avoiding the need for synchronisation.




    • You can use more than one semaphore. Where each thread, explicitly hands control to the next.


    • You can have a Whose-turn-is-next variable. After getting the lock, a thread will check to see if it is its turn, if not it will free the lock. This could result in spinning, doing nothing. So we would have to add another lock. After checking we would wait on another lock has-somethread-finished. This will be freed after a thread has done some work. Now threads don't spin. However every time a thread finishes, every other thread will check to see if it is next.



    The solutions so far while directly answering your question, are anti-patterns. You are just making a multi-threaded program, run single threaded, by using semaphores to fully synchronise the threads.



    This one is nether a pattern or anti-pattern, just a note




    • On Unix a thread will eventually get de-scheduled, if it hogs the processor, and there are other threads ready to run.


    Better ways to do it.




    • Avoid need for synchronisation:

      (see https://www.youtube.com/watch?v=2yXtZ8x7TXw) If you don't use mutable variables, then concurrency is easy, and there is no need for synchronisation.


    • Consider pipes and filters: in this pattern threads can communicate via a pipe (fifo). You can use a minimal locking circular buffer for this (just ensure that you only put immutable data into the buffer). |In Unixes (such as Gnu/Linux), you can use pipes and processes. You can do this all within one program, using fork. Or you can connect several programs together (bash is a good tool for this).


    • Consider micro-threads / co-routines / co-operative threads:

      Sometimes it is nice to write a program with several independent threads. But if your threads do not spend a significant amount of time running concurrently (for example because you always call signal; wait), then you do not need threads. And threads produce a significant amount of complexity to the code. Therefore use co-routines (or what ever they are called on your system), they allow you to write several routines to be scheduled independently, but control will only be handed over to another co-routine when yield is called (similar to calling signal; wait, but the mechanism will prefer to hand over to the next co-routine in the ring.







    share|improve this answer






























      0














      Here are some options. Because you are always calling signal immediately followed by wait, the co-routine option is probably the best. You have no parallelisable code, so can not benefit from normal threads. It will also be useful to learn about avoiding the need for synchronisation.




      • You can use more than one semaphore. Where each thread, explicitly hands control to the next.


      • You can have a Whose-turn-is-next variable. After getting the lock, a thread will check to see if it is its turn, if not it will free the lock. This could result in spinning, doing nothing. So we would have to add another lock. After checking we would wait on another lock has-somethread-finished. This will be freed after a thread has done some work. Now threads don't spin. However every time a thread finishes, every other thread will check to see if it is next.



      The solutions so far while directly answering your question, are anti-patterns. You are just making a multi-threaded program, run single threaded, by using semaphores to fully synchronise the threads.



      This one is nether a pattern or anti-pattern, just a note




      • On Unix a thread will eventually get de-scheduled, if it hogs the processor, and there are other threads ready to run.


      Better ways to do it.




      • Avoid need for synchronisation:

        (see https://www.youtube.com/watch?v=2yXtZ8x7TXw) If you don't use mutable variables, then concurrency is easy, and there is no need for synchronisation.


      • Consider pipes and filters: in this pattern threads can communicate via a pipe (fifo). You can use a minimal locking circular buffer for this (just ensure that you only put immutable data into the buffer). |In Unixes (such as Gnu/Linux), you can use pipes and processes. You can do this all within one program, using fork. Or you can connect several programs together (bash is a good tool for this).


      • Consider micro-threads / co-routines / co-operative threads:

        Sometimes it is nice to write a program with several independent threads. But if your threads do not spend a significant amount of time running concurrently (for example because you always call signal; wait), then you do not need threads. And threads produce a significant amount of complexity to the code. Therefore use co-routines (or what ever they are called on your system), they allow you to write several routines to be scheduled independently, but control will only be handed over to another co-routine when yield is called (similar to calling signal; wait, but the mechanism will prefer to hand over to the next co-routine in the ring.







      share|improve this answer




























        0












        0








        0







        Here are some options. Because you are always calling signal immediately followed by wait, the co-routine option is probably the best. You have no parallelisable code, so can not benefit from normal threads. It will also be useful to learn about avoiding the need for synchronisation.




        • You can use more than one semaphore. Where each thread, explicitly hands control to the next.


        • You can have a Whose-turn-is-next variable. After getting the lock, a thread will check to see if it is its turn, if not it will free the lock. This could result in spinning, doing nothing. So we would have to add another lock. After checking we would wait on another lock has-somethread-finished. This will be freed after a thread has done some work. Now threads don't spin. However every time a thread finishes, every other thread will check to see if it is next.



        The solutions so far while directly answering your question, are anti-patterns. You are just making a multi-threaded program, run single threaded, by using semaphores to fully synchronise the threads.



        This one is nether a pattern or anti-pattern, just a note




        • On Unix a thread will eventually get de-scheduled, if it hogs the processor, and there are other threads ready to run.


        Better ways to do it.




        • Avoid need for synchronisation:

          (see https://www.youtube.com/watch?v=2yXtZ8x7TXw) If you don't use mutable variables, then concurrency is easy, and there is no need for synchronisation.


        • Consider pipes and filters: in this pattern threads can communicate via a pipe (fifo). You can use a minimal locking circular buffer for this (just ensure that you only put immutable data into the buffer). |In Unixes (such as Gnu/Linux), you can use pipes and processes. You can do this all within one program, using fork. Or you can connect several programs together (bash is a good tool for this).


        • Consider micro-threads / co-routines / co-operative threads:

          Sometimes it is nice to write a program with several independent threads. But if your threads do not spend a significant amount of time running concurrently (for example because you always call signal; wait), then you do not need threads. And threads produce a significant amount of complexity to the code. Therefore use co-routines (or what ever they are called on your system), they allow you to write several routines to be scheduled independently, but control will only be handed over to another co-routine when yield is called (similar to calling signal; wait, but the mechanism will prefer to hand over to the next co-routine in the ring.







        share|improve this answer















        Here are some options. Because you are always calling signal immediately followed by wait, the co-routine option is probably the best. You have no parallelisable code, so can not benefit from normal threads. It will also be useful to learn about avoiding the need for synchronisation.




        • You can use more than one semaphore. Where each thread, explicitly hands control to the next.


        • You can have a Whose-turn-is-next variable. After getting the lock, a thread will check to see if it is its turn, if not it will free the lock. This could result in spinning, doing nothing. So we would have to add another lock. After checking we would wait on another lock has-somethread-finished. This will be freed after a thread has done some work. Now threads don't spin. However every time a thread finishes, every other thread will check to see if it is next.



        The solutions so far while directly answering your question, are anti-patterns. You are just making a multi-threaded program, run single threaded, by using semaphores to fully synchronise the threads.



        This one is nether a pattern or anti-pattern, just a note




        • On Unix a thread will eventually get de-scheduled, if it hogs the processor, and there are other threads ready to run.


        Better ways to do it.




        • Avoid need for synchronisation:

          (see https://www.youtube.com/watch?v=2yXtZ8x7TXw) If you don't use mutable variables, then concurrency is easy, and there is no need for synchronisation.


        • Consider pipes and filters: in this pattern threads can communicate via a pipe (fifo). You can use a minimal locking circular buffer for this (just ensure that you only put immutable data into the buffer). |In Unixes (such as Gnu/Linux), you can use pipes and processes. You can do this all within one program, using fork. Or you can connect several programs together (bash is a good tool for this).


        • Consider micro-threads / co-routines / co-operative threads:

          Sometimes it is nice to write a program with several independent threads. But if your threads do not spend a significant amount of time running concurrently (for example because you always call signal; wait), then you do not need threads. And threads produce a significant amount of complexity to the code. Therefore use co-routines (or what ever they are called on your system), they allow you to write several routines to be scheduled independently, but control will only be handed over to another co-routine when yield is called (similar to calling signal; wait, but the mechanism will prefer to hand over to the next co-routine in the ring.








        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited Nov 25 '18 at 13:12

























        answered Nov 25 '18 at 9:18









        ctrl-alt-delorctrl-alt-delor

        4,34732644




        4,34732644
































            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%2f53459742%2fsync-n-processes-using-semaphore-condition-race%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







            這個網誌中的熱門文章

            Hercules Kyvelos

            Tangent Lines Diagram Along Smooth Curve

            Yusuf al-Mu'taman ibn Hud