Using std::thread to call functions from two Classes in C++11












0















I am trying to implement an API that should let the user create two communication channels in parallel. One channel uses TCP and the other uses UDP. I have two classes representing the two channels. These classes have different functions implemented. I would like the functions from the two channels to run in parallel. For that I am using std::thread to create two threads, one for each channel (class).
The idea is the following following
The header file looks like



class Channel_1
{
public:
int myfunc(int a, int b);
};

class Channel_2
{
public:
int anotherfunc(int a, int b);
};


In the main cpp file
include the header file



int main()
{
int a = 10, b = 20;
Channel_1 ch1;
Channel_2 ch2;

std::thread t(ch1.myfunc, a,b);
return 0;
}


I get the error saying that no instance of the constructor std::thread exists.



I have the following questions.




  1. Can't we call the functions from a class in the thread
    constructor?

  2. Does this idea of using threads for calling functions from different classes make sense?










share|improve this question





























    0















    I am trying to implement an API that should let the user create two communication channels in parallel. One channel uses TCP and the other uses UDP. I have two classes representing the two channels. These classes have different functions implemented. I would like the functions from the two channels to run in parallel. For that I am using std::thread to create two threads, one for each channel (class).
    The idea is the following following
    The header file looks like



    class Channel_1
    {
    public:
    int myfunc(int a, int b);
    };

    class Channel_2
    {
    public:
    int anotherfunc(int a, int b);
    };


    In the main cpp file
    include the header file



    int main()
    {
    int a = 10, b = 20;
    Channel_1 ch1;
    Channel_2 ch2;

    std::thread t(ch1.myfunc, a,b);
    return 0;
    }


    I get the error saying that no instance of the constructor std::thread exists.



    I have the following questions.




    1. Can't we call the functions from a class in the thread
      constructor?

    2. Does this idea of using threads for calling functions from different classes make sense?










    share|improve this question



























      0












      0








      0








      I am trying to implement an API that should let the user create two communication channels in parallel. One channel uses TCP and the other uses UDP. I have two classes representing the two channels. These classes have different functions implemented. I would like the functions from the two channels to run in parallel. For that I am using std::thread to create two threads, one for each channel (class).
      The idea is the following following
      The header file looks like



      class Channel_1
      {
      public:
      int myfunc(int a, int b);
      };

      class Channel_2
      {
      public:
      int anotherfunc(int a, int b);
      };


      In the main cpp file
      include the header file



      int main()
      {
      int a = 10, b = 20;
      Channel_1 ch1;
      Channel_2 ch2;

      std::thread t(ch1.myfunc, a,b);
      return 0;
      }


      I get the error saying that no instance of the constructor std::thread exists.



      I have the following questions.




      1. Can't we call the functions from a class in the thread
        constructor?

      2. Does this idea of using threads for calling functions from different classes make sense?










      share|improve this question
















      I am trying to implement an API that should let the user create two communication channels in parallel. One channel uses TCP and the other uses UDP. I have two classes representing the two channels. These classes have different functions implemented. I would like the functions from the two channels to run in parallel. For that I am using std::thread to create two threads, one for each channel (class).
      The idea is the following following
      The header file looks like



      class Channel_1
      {
      public:
      int myfunc(int a, int b);
      };

      class Channel_2
      {
      public:
      int anotherfunc(int a, int b);
      };


      In the main cpp file
      include the header file



      int main()
      {
      int a = 10, b = 20;
      Channel_1 ch1;
      Channel_2 ch2;

      std::thread t(ch1.myfunc, a,b);
      return 0;
      }


      I get the error saying that no instance of the constructor std::thread exists.



      I have the following questions.




      1. Can't we call the functions from a class in the thread
        constructor?

      2. Does this idea of using threads for calling functions from different classes make sense?







      c++ multithreading sockets c++11 stdthread






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Nov 13 '18 at 14:12









      JBL

      9,71333667




      9,71333667










      asked Nov 13 '18 at 14:09









      D_wanna_B_coderD_wanna_B_coder

      195




      195
























          2 Answers
          2






          active

          oldest

          votes


















          6














          You actually have two problems:





          1. The syntax is wrong. You need to pass a pointer to the member function, as in



            std::thread t(&Channel_1::myfunc, a, b);



          2. Non-static member functions needs to be called on an instance of the class. This instance must be passed as the first argument:



            std::thread t(&Channel_1::myfunc, ch1, a, b);







          share|improve this answer































            0














            As Some programmer dude said, you need to supply a pointer to the function (either a static or non-static). A third option could be to make a base class that implements a start() method that uses this thread constructor:



            template< class Function, class... Args > 
            explicit thread( Function&& f, Args&&... args );


            Example using a lambda. It's not meant to be a complete working example, It's only meant to show how the third thread constructor could be used.



            class thread_base {
            private:
            std::thread m_th;
            bool m_terminated;

            void proxy() {
            // in the new thread
            // add thread_base setup here if needed and
            // call the execute() method in the derived class
            execute();
            }
            public:
            thread_base() : m_th(), m_terminated(false) {}
            thread_base(const thread_base&) = delete;
            thread_base& operator=(const thread_base&) = delete;
            thread_base(thread_base&&) = default;
            thread_base& operator=(thread_base&&) = default;
            virtual ~thread_base() { join(); }

            virtual void start() {
            if(joinable()) throw std::runtime_error("thread already running");
            else m_th = std::thread( [this] { proxy(); } );
            }

            inline bool joinable() { return m_th.joinable(); }
            inline void join() { if(joinable()) { m_th.join(); m_terminated=false; } }
            inline void terminate() { m_terminated=true; }
            inline bool terminated() { return m_terminated; }

            virtual void execute() = 0; // implement this in your derived classes
            };


            class Channel_1 : public thread_base {
            void execute() {
            // runs in a thread
            // with a volontary check if a soft termination
            // request has been issued
            while( !terminated() ) {
            // work
            }
            }
            };





            share|improve this answer


























            • A virtual final member in the base class?

              – SergeyA
              Nov 13 '18 at 14:43











            • Yeah, it should be public and not possible to override. This was the first I thought of but perhaps there's a better way.

              – Ted Lyngmo
              Nov 13 '18 at 14:51











            • Is the downvote for the virtual final member or something else?

              – Ted Lyngmo
              Nov 13 '18 at 14:52











            • For virtual final method in base, for immediate core dump due to destructor of temporary std::thread called on non-joined thread, for unnecessary complexity.

              – SergeyA
              Nov 13 '18 at 14:55











            • Ok, it was not a complete working base class, but rather something to show how the third thread constructor could be used. I added a little more boilerplate (still not a complete base class though). As for the virtual final method, I don't know of another way of preventing it from being overridden.

              – Ted Lyngmo
              Nov 13 '18 at 15:22











            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%2f53282876%2fusing-stdthread-to-call-functions-from-two-classes-in-c11%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown

























            2 Answers
            2






            active

            oldest

            votes








            2 Answers
            2






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            6














            You actually have two problems:





            1. The syntax is wrong. You need to pass a pointer to the member function, as in



              std::thread t(&Channel_1::myfunc, a, b);



            2. Non-static member functions needs to be called on an instance of the class. This instance must be passed as the first argument:



              std::thread t(&Channel_1::myfunc, ch1, a, b);







            share|improve this answer




























              6














              You actually have two problems:





              1. The syntax is wrong. You need to pass a pointer to the member function, as in



                std::thread t(&Channel_1::myfunc, a, b);



              2. Non-static member functions needs to be called on an instance of the class. This instance must be passed as the first argument:



                std::thread t(&Channel_1::myfunc, ch1, a, b);







              share|improve this answer


























                6












                6








                6







                You actually have two problems:





                1. The syntax is wrong. You need to pass a pointer to the member function, as in



                  std::thread t(&Channel_1::myfunc, a, b);



                2. Non-static member functions needs to be called on an instance of the class. This instance must be passed as the first argument:



                  std::thread t(&Channel_1::myfunc, ch1, a, b);







                share|improve this answer













                You actually have two problems:





                1. The syntax is wrong. You need to pass a pointer to the member function, as in



                  std::thread t(&Channel_1::myfunc, a, b);



                2. Non-static member functions needs to be called on an instance of the class. This instance must be passed as the first argument:



                  std::thread t(&Channel_1::myfunc, ch1, a, b);








                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Nov 13 '18 at 14:12









                Some programmer dudeSome programmer dude

                296k24250412




                296k24250412

























                    0














                    As Some programmer dude said, you need to supply a pointer to the function (either a static or non-static). A third option could be to make a base class that implements a start() method that uses this thread constructor:



                    template< class Function, class... Args > 
                    explicit thread( Function&& f, Args&&... args );


                    Example using a lambda. It's not meant to be a complete working example, It's only meant to show how the third thread constructor could be used.



                    class thread_base {
                    private:
                    std::thread m_th;
                    bool m_terminated;

                    void proxy() {
                    // in the new thread
                    // add thread_base setup here if needed and
                    // call the execute() method in the derived class
                    execute();
                    }
                    public:
                    thread_base() : m_th(), m_terminated(false) {}
                    thread_base(const thread_base&) = delete;
                    thread_base& operator=(const thread_base&) = delete;
                    thread_base(thread_base&&) = default;
                    thread_base& operator=(thread_base&&) = default;
                    virtual ~thread_base() { join(); }

                    virtual void start() {
                    if(joinable()) throw std::runtime_error("thread already running");
                    else m_th = std::thread( [this] { proxy(); } );
                    }

                    inline bool joinable() { return m_th.joinable(); }
                    inline void join() { if(joinable()) { m_th.join(); m_terminated=false; } }
                    inline void terminate() { m_terminated=true; }
                    inline bool terminated() { return m_terminated; }

                    virtual void execute() = 0; // implement this in your derived classes
                    };


                    class Channel_1 : public thread_base {
                    void execute() {
                    // runs in a thread
                    // with a volontary check if a soft termination
                    // request has been issued
                    while( !terminated() ) {
                    // work
                    }
                    }
                    };





                    share|improve this answer


























                    • A virtual final member in the base class?

                      – SergeyA
                      Nov 13 '18 at 14:43











                    • Yeah, it should be public and not possible to override. This was the first I thought of but perhaps there's a better way.

                      – Ted Lyngmo
                      Nov 13 '18 at 14:51











                    • Is the downvote for the virtual final member or something else?

                      – Ted Lyngmo
                      Nov 13 '18 at 14:52











                    • For virtual final method in base, for immediate core dump due to destructor of temporary std::thread called on non-joined thread, for unnecessary complexity.

                      – SergeyA
                      Nov 13 '18 at 14:55











                    • Ok, it was not a complete working base class, but rather something to show how the third thread constructor could be used. I added a little more boilerplate (still not a complete base class though). As for the virtual final method, I don't know of another way of preventing it from being overridden.

                      – Ted Lyngmo
                      Nov 13 '18 at 15:22
















                    0














                    As Some programmer dude said, you need to supply a pointer to the function (either a static or non-static). A third option could be to make a base class that implements a start() method that uses this thread constructor:



                    template< class Function, class... Args > 
                    explicit thread( Function&& f, Args&&... args );


                    Example using a lambda. It's not meant to be a complete working example, It's only meant to show how the third thread constructor could be used.



                    class thread_base {
                    private:
                    std::thread m_th;
                    bool m_terminated;

                    void proxy() {
                    // in the new thread
                    // add thread_base setup here if needed and
                    // call the execute() method in the derived class
                    execute();
                    }
                    public:
                    thread_base() : m_th(), m_terminated(false) {}
                    thread_base(const thread_base&) = delete;
                    thread_base& operator=(const thread_base&) = delete;
                    thread_base(thread_base&&) = default;
                    thread_base& operator=(thread_base&&) = default;
                    virtual ~thread_base() { join(); }

                    virtual void start() {
                    if(joinable()) throw std::runtime_error("thread already running");
                    else m_th = std::thread( [this] { proxy(); } );
                    }

                    inline bool joinable() { return m_th.joinable(); }
                    inline void join() { if(joinable()) { m_th.join(); m_terminated=false; } }
                    inline void terminate() { m_terminated=true; }
                    inline bool terminated() { return m_terminated; }

                    virtual void execute() = 0; // implement this in your derived classes
                    };


                    class Channel_1 : public thread_base {
                    void execute() {
                    // runs in a thread
                    // with a volontary check if a soft termination
                    // request has been issued
                    while( !terminated() ) {
                    // work
                    }
                    }
                    };





                    share|improve this answer


























                    • A virtual final member in the base class?

                      – SergeyA
                      Nov 13 '18 at 14:43











                    • Yeah, it should be public and not possible to override. This was the first I thought of but perhaps there's a better way.

                      – Ted Lyngmo
                      Nov 13 '18 at 14:51











                    • Is the downvote for the virtual final member or something else?

                      – Ted Lyngmo
                      Nov 13 '18 at 14:52











                    • For virtual final method in base, for immediate core dump due to destructor of temporary std::thread called on non-joined thread, for unnecessary complexity.

                      – SergeyA
                      Nov 13 '18 at 14:55











                    • Ok, it was not a complete working base class, but rather something to show how the third thread constructor could be used. I added a little more boilerplate (still not a complete base class though). As for the virtual final method, I don't know of another way of preventing it from being overridden.

                      – Ted Lyngmo
                      Nov 13 '18 at 15:22














                    0












                    0








                    0







                    As Some programmer dude said, you need to supply a pointer to the function (either a static or non-static). A third option could be to make a base class that implements a start() method that uses this thread constructor:



                    template< class Function, class... Args > 
                    explicit thread( Function&& f, Args&&... args );


                    Example using a lambda. It's not meant to be a complete working example, It's only meant to show how the third thread constructor could be used.



                    class thread_base {
                    private:
                    std::thread m_th;
                    bool m_terminated;

                    void proxy() {
                    // in the new thread
                    // add thread_base setup here if needed and
                    // call the execute() method in the derived class
                    execute();
                    }
                    public:
                    thread_base() : m_th(), m_terminated(false) {}
                    thread_base(const thread_base&) = delete;
                    thread_base& operator=(const thread_base&) = delete;
                    thread_base(thread_base&&) = default;
                    thread_base& operator=(thread_base&&) = default;
                    virtual ~thread_base() { join(); }

                    virtual void start() {
                    if(joinable()) throw std::runtime_error("thread already running");
                    else m_th = std::thread( [this] { proxy(); } );
                    }

                    inline bool joinable() { return m_th.joinable(); }
                    inline void join() { if(joinable()) { m_th.join(); m_terminated=false; } }
                    inline void terminate() { m_terminated=true; }
                    inline bool terminated() { return m_terminated; }

                    virtual void execute() = 0; // implement this in your derived classes
                    };


                    class Channel_1 : public thread_base {
                    void execute() {
                    // runs in a thread
                    // with a volontary check if a soft termination
                    // request has been issued
                    while( !terminated() ) {
                    // work
                    }
                    }
                    };





                    share|improve this answer















                    As Some programmer dude said, you need to supply a pointer to the function (either a static or non-static). A third option could be to make a base class that implements a start() method that uses this thread constructor:



                    template< class Function, class... Args > 
                    explicit thread( Function&& f, Args&&... args );


                    Example using a lambda. It's not meant to be a complete working example, It's only meant to show how the third thread constructor could be used.



                    class thread_base {
                    private:
                    std::thread m_th;
                    bool m_terminated;

                    void proxy() {
                    // in the new thread
                    // add thread_base setup here if needed and
                    // call the execute() method in the derived class
                    execute();
                    }
                    public:
                    thread_base() : m_th(), m_terminated(false) {}
                    thread_base(const thread_base&) = delete;
                    thread_base& operator=(const thread_base&) = delete;
                    thread_base(thread_base&&) = default;
                    thread_base& operator=(thread_base&&) = default;
                    virtual ~thread_base() { join(); }

                    virtual void start() {
                    if(joinable()) throw std::runtime_error("thread already running");
                    else m_th = std::thread( [this] { proxy(); } );
                    }

                    inline bool joinable() { return m_th.joinable(); }
                    inline void join() { if(joinable()) { m_th.join(); m_terminated=false; } }
                    inline void terminate() { m_terminated=true; }
                    inline bool terminated() { return m_terminated; }

                    virtual void execute() = 0; // implement this in your derived classes
                    };


                    class Channel_1 : public thread_base {
                    void execute() {
                    // runs in a thread
                    // with a volontary check if a soft termination
                    // request has been issued
                    while( !terminated() ) {
                    // work
                    }
                    }
                    };






                    share|improve this answer














                    share|improve this answer



                    share|improve this answer








                    edited Nov 13 '18 at 17:28

























                    answered Nov 13 '18 at 14:33









                    Ted LyngmoTed Lyngmo

                    2,1961317




                    2,1961317













                    • A virtual final member in the base class?

                      – SergeyA
                      Nov 13 '18 at 14:43











                    • Yeah, it should be public and not possible to override. This was the first I thought of but perhaps there's a better way.

                      – Ted Lyngmo
                      Nov 13 '18 at 14:51











                    • Is the downvote for the virtual final member or something else?

                      – Ted Lyngmo
                      Nov 13 '18 at 14:52











                    • For virtual final method in base, for immediate core dump due to destructor of temporary std::thread called on non-joined thread, for unnecessary complexity.

                      – SergeyA
                      Nov 13 '18 at 14:55











                    • Ok, it was not a complete working base class, but rather something to show how the third thread constructor could be used. I added a little more boilerplate (still not a complete base class though). As for the virtual final method, I don't know of another way of preventing it from being overridden.

                      – Ted Lyngmo
                      Nov 13 '18 at 15:22



















                    • A virtual final member in the base class?

                      – SergeyA
                      Nov 13 '18 at 14:43











                    • Yeah, it should be public and not possible to override. This was the first I thought of but perhaps there's a better way.

                      – Ted Lyngmo
                      Nov 13 '18 at 14:51











                    • Is the downvote for the virtual final member or something else?

                      – Ted Lyngmo
                      Nov 13 '18 at 14:52











                    • For virtual final method in base, for immediate core dump due to destructor of temporary std::thread called on non-joined thread, for unnecessary complexity.

                      – SergeyA
                      Nov 13 '18 at 14:55











                    • Ok, it was not a complete working base class, but rather something to show how the third thread constructor could be used. I added a little more boilerplate (still not a complete base class though). As for the virtual final method, I don't know of another way of preventing it from being overridden.

                      – Ted Lyngmo
                      Nov 13 '18 at 15:22

















                    A virtual final member in the base class?

                    – SergeyA
                    Nov 13 '18 at 14:43





                    A virtual final member in the base class?

                    – SergeyA
                    Nov 13 '18 at 14:43













                    Yeah, it should be public and not possible to override. This was the first I thought of but perhaps there's a better way.

                    – Ted Lyngmo
                    Nov 13 '18 at 14:51





                    Yeah, it should be public and not possible to override. This was the first I thought of but perhaps there's a better way.

                    – Ted Lyngmo
                    Nov 13 '18 at 14:51













                    Is the downvote for the virtual final member or something else?

                    – Ted Lyngmo
                    Nov 13 '18 at 14:52





                    Is the downvote for the virtual final member or something else?

                    – Ted Lyngmo
                    Nov 13 '18 at 14:52













                    For virtual final method in base, for immediate core dump due to destructor of temporary std::thread called on non-joined thread, for unnecessary complexity.

                    – SergeyA
                    Nov 13 '18 at 14:55





                    For virtual final method in base, for immediate core dump due to destructor of temporary std::thread called on non-joined thread, for unnecessary complexity.

                    – SergeyA
                    Nov 13 '18 at 14:55













                    Ok, it was not a complete working base class, but rather something to show how the third thread constructor could be used. I added a little more boilerplate (still not a complete base class though). As for the virtual final method, I don't know of another way of preventing it from being overridden.

                    – Ted Lyngmo
                    Nov 13 '18 at 15:22





                    Ok, it was not a complete working base class, but rather something to show how the third thread constructor could be used. I added a little more boilerplate (still not a complete base class though). As for the virtual final method, I don't know of another way of preventing it from being overridden.

                    – Ted Lyngmo
                    Nov 13 '18 at 15:22


















                    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%2f53282876%2fusing-stdthread-to-call-functions-from-two-classes-in-c11%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

                    Xamarin.iOS Cant Deploy on Iphone

                    Glorious Revolution

                    Dulmage-Mendelsohn matrix decomposition in Python