Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. General Programming
  3. ATL / WTL / STL
  4. use of beginthreadex()

use of beginthreadex()

Scheduled Pinned Locked Moved ATL / WTL / STL
c++visual-studioquestioncsharpcom
12 Posts 3 Posters 33 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • B Offline
    B Offline
    bkelly13
    wrote on last edited by
    #1

    Windows 7, Visual Studio 2008, C++, not managed code So far, it seems that the best way to start a thread is with this:

    uintptr_t _beginthreadex( // NATIVE CODE
    void *security,
    unsigned stack_size,
    unsigned ( __stdcall *start_address )( void * ),
    void *arglist,
    unsigned initflag,
    unsigned *thrdaddr
    );

    found here: http://msdn.microsoft.com/en-us/library/kdzttdcb(v=vs.90).aspx[^] I found the article in CodeProject about starting a class as the thread and am using that. The one argument to the thread is the address of a structure used to pass data between the main app and the thread. Call it common_structure. The method that will be started is Main_TCP_Class( void * common_struct ){...} (This class will handle my TCP/IP work and that thread will run for the duration so it seems Main_TCP_Class() is an aptly descriptive name.) Question: Does the act of starting the thread with _beginthreadex(...) instantiate the class? If not, there will be some follow up questions on this. If so, that would mean, I presume, that the constructor runs before method Main_TCP_Class() runs. And that means that none of the data in common_structure is accessible until Main_TCP_Class has started and has captured the pointer in the argument. Is this correct? Any pitfalls that I should be aware of?

    Thanks for your time If you work with telemetry, please check this bulletin board: http://www.bkelly.ws/irig\_106/

    L 1 Reply Last reply
    0
    • B bkelly13

      Windows 7, Visual Studio 2008, C++, not managed code So far, it seems that the best way to start a thread is with this:

      uintptr_t _beginthreadex( // NATIVE CODE
      void *security,
      unsigned stack_size,
      unsigned ( __stdcall *start_address )( void * ),
      void *arglist,
      unsigned initflag,
      unsigned *thrdaddr
      );

      found here: http://msdn.microsoft.com/en-us/library/kdzttdcb(v=vs.90).aspx[^] I found the article in CodeProject about starting a class as the thread and am using that. The one argument to the thread is the address of a structure used to pass data between the main app and the thread. Call it common_structure. The method that will be started is Main_TCP_Class( void * common_struct ){...} (This class will handle my TCP/IP work and that thread will run for the duration so it seems Main_TCP_Class() is an aptly descriptive name.) Question: Does the act of starting the thread with _beginthreadex(...) instantiate the class? If not, there will be some follow up questions on this. If so, that would mean, I presume, that the constructor runs before method Main_TCP_Class() runs. And that means that none of the data in common_structure is accessible until Main_TCP_Class has started and has captured the pointer in the argument. Is this correct? Any pitfalls that I should be aware of?

      Thanks for your time If you work with telemetry, please check this bulletin board: http://www.bkelly.ws/irig\_106/

      L Offline
      L Offline
      Lost User
      wrote on last edited by
      #2

      bkelly13 wrote:

      Does the act of starting the thread with _beginthreadex(...) instantiate the class?

      No, it merely starts the thread at the address pointed to by start_address. You may be better using the CreateThread[^] call, which is more closely integrated to the Win32 API. Neither _beginthreadex nor CreateThread have any knowledge of the structure of your program, in terms of classes and other structures.

      Veni, vidi, abiit domum

      B 1 Reply Last reply
      0
      • L Lost User

        bkelly13 wrote:

        Does the act of starting the thread with _beginthreadex(...) instantiate the class?

        No, it merely starts the thread at the address pointed to by start_address. You may be better using the CreateThread[^] call, which is more closely integrated to the Win32 API. Neither _beginthreadex nor CreateThread have any knowledge of the structure of your program, in terms of classes and other structures.

        Veni, vidi, abiit domum

        B Offline
        B Offline
        bkelly13
        wrote on last edited by
        #3

        RE: No, it merely starts the thread at the address pointed to by start_address. That makes sense, the class must be instantiated before passing in the one method to CreateThread(). But, since the main app has created the class and has its address, what prohibits the main app from calling methods in the class? Yes, I am mostly aware of problems that may cause. My intent is to call methods such as:

        Set_Logging_Flag( bool new_value );
        bool Get_Logging_Flag();

        These methods would just set flags that the thread would detect then act upon. Note that I wrote "mostly aware of" as I am certain there are things of which I am not aware. Edit shortly later: Following the codeproject article resulted in the following in the dot H file:

        // This is the function that is to run as a separate thread.
        void Main_TCP_Class( void * common_structure );

        static unsigned __stdcall ThreadStaticEntryPoint( void * pThis )
        {
        C_Server_TCP_Win_Api * p_C_Server_TCP_Win_Api = (C_Server_TCP_Win_Api * )pThis;
        p_C_Server_TCP_Win_Api->Main_TCP_Class( m_common_data );
        return 1;
        ...

        static st_server_tcp_common_structure *m_common_data;
        }

        The compile failed until I declared the common structure static. OK. But one of the goals was to pass one argument to the thread and that argument could be a structure through which the main app communicates with the thread. Possible Revelation: Since we declare that structure as static, and the main app instantiates the class before starting it as a thread, it has access to that static class regardless of how the class is run. So why go through all this to pass the argument?

        Thanks for your time If you work with telemetry, please check this bulletin board: http://www.bkelly.ws/irig\_106/

        L 1 Reply Last reply
        0
        • B bkelly13

          RE: No, it merely starts the thread at the address pointed to by start_address. That makes sense, the class must be instantiated before passing in the one method to CreateThread(). But, since the main app has created the class and has its address, what prohibits the main app from calling methods in the class? Yes, I am mostly aware of problems that may cause. My intent is to call methods such as:

          Set_Logging_Flag( bool new_value );
          bool Get_Logging_Flag();

          These methods would just set flags that the thread would detect then act upon. Note that I wrote "mostly aware of" as I am certain there are things of which I am not aware. Edit shortly later: Following the codeproject article resulted in the following in the dot H file:

          // This is the function that is to run as a separate thread.
          void Main_TCP_Class( void * common_structure );

          static unsigned __stdcall ThreadStaticEntryPoint( void * pThis )
          {
          C_Server_TCP_Win_Api * p_C_Server_TCP_Win_Api = (C_Server_TCP_Win_Api * )pThis;
          p_C_Server_TCP_Win_Api->Main_TCP_Class( m_common_data );
          return 1;
          ...

          static st_server_tcp_common_structure *m_common_data;
          }

          The compile failed until I declared the common structure static. OK. But one of the goals was to pass one argument to the thread and that argument could be a structure through which the main app communicates with the thread. Possible Revelation: Since we declare that structure as static, and the main app instantiates the class before starting it as a thread, it has access to that static class regardless of how the class is run. So why go through all this to pass the argument?

          Thanks for your time If you work with telemetry, please check this bulletin board: http://www.bkelly.ws/irig\_106/

          L Offline
          L Offline
          Lost User
          wrote on last edited by
          #4

          bkelly13 wrote:

          what prohibits the main app from calling methods in the class?

          Nothing at all, but those methods will be running in a different thread so will have no effect on the thread that you previously started. Threads communicate by using common areas of memory, and they must each synchronise their actions so they don't corrupt the space.

          bkelly13 wrote:

          Following the codeproject article

          Questions about articles are best posted in the forum at the end of the article; the author is the best person to answer questions on the structure of their code.

          Veni, vidi, abiit domum

          B 1 Reply Last reply
          0
          • L Lost User

            bkelly13 wrote:

            what prohibits the main app from calling methods in the class?

            Nothing at all, but those methods will be running in a different thread so will have no effect on the thread that you previously started. Threads communicate by using common areas of memory, and they must each synchronise their actions so they don't corrupt the space.

            bkelly13 wrote:

            Following the codeproject article

            Questions about articles are best posted in the forum at the end of the article; the author is the best person to answer questions on the structure of their code.

            Veni, vidi, abiit domum

            B Offline
            B Offline
            bkelly13
            wrote on last edited by
            #5

            Hello, I have a point of confusion here. In response to my question you wrote:

            Quote:

            No, it merely starts the thread at the address pointed to by start_address.

            I concluded that CreateThread would not create an instance of the class, just start it running as a separate thread. From that I conclude I must instantiate the class then start it as a separate thread. If that is so then calls to that class would be in the same address space. If not, then why would I instantiate it before calling CreateThread? In either case I don't know what will happen. I had some difficulties with the code I was writing so I stripped it down to the bare bones of nothing more that being able to start a thread. I will be working with that in the meantime.

            Thanks for your time If you work with telemetry, please check this bulletin board: http://www.bkelly.ws/irig\_106/

            L 1 Reply Last reply
            0
            • B bkelly13

              Hello, I have a point of confusion here. In response to my question you wrote:

              Quote:

              No, it merely starts the thread at the address pointed to by start_address.

              I concluded that CreateThread would not create an instance of the class, just start it running as a separate thread. From that I conclude I must instantiate the class then start it as a separate thread. If that is so then calls to that class would be in the same address space. If not, then why would I instantiate it before calling CreateThread? In either case I don't know what will happen. I had some difficulties with the code I was writing so I stripped it down to the bare bones of nothing more that being able to start a thread. I will be working with that in the meantime.

              Thanks for your time If you work with telemetry, please check this bulletin board: http://www.bkelly.ws/irig\_106/

              L Offline
              L Offline
              Lost User
              wrote on last edited by
              #6

              As you say, CreateThread would not create an instance of the class. This function creates a new process which runs in parallel with the currently running code, starting at the address given. Within the new process you can create new objects of a class and run their methods, while other objects are actioned in the main thread. As I said before, there is no communication between the two processes except by passing information through shared memory. You may find it easier to run your separate thread as pure procedural code rather than as classes. But that will, of course, depend on what the code is actually doing.

              Veni, vidi, abiit domum

              B 1 Reply Last reply
              0
              • L Lost User

                As you say, CreateThread would not create an instance of the class. This function creates a new process which runs in parallel with the currently running code, starting at the address given. Within the new process you can create new objects of a class and run their methods, while other objects are actioned in the main thread. As I said before, there is no communication between the two processes except by passing information through shared memory. You may find it easier to run your separate thread as pure procedural code rather than as classes. But that will, of course, depend on what the code is actually doing.

                Veni, vidi, abiit domum

                B Offline
                B Offline
                bkelly13
                wrote on last edited by
                #7

                Hello, Re:

                Quote:

                You may find it easier to run your separate thread as pure procedural code rather than as classes. But that will, of course, depend on what the code is actually doing.

                I have been thinking about that quite a bit. It would probably be easier to start the process as a single procedure not wrapped up in a class. But, this is for TCP/IP and there is quite a lot to do. I suppose everything could be free standing functions, but that would require a single monster procedure or require a flock of arguments for every call. Being a single person software team where I work has some advantages, but they are truly overwhelmed by the disadvantage of not having anyone to discuss ideas with. I think I will go to a single simple function to test out the concepts and try to get some events working. Then I will return to the TCP/IP part of this. Working one problem area at a time will make this easier. Thank you for your thoughts. EDIT: I have worked this on and off through the day. The current status is that creating a simple thread with some events using a free standing procedure is easier than I thought and easier that it looks. Putting a TCP/IP manager in a single procedure would probably get ugly. Right now my next step is to see what it takes to put this one procedure in a class and start it as a thread. Would this be worth writing up as a series of articles? Article 1: Simple thread, 2: Thread from a class, 3: TCP/IP as a separate thread.

                Thanks for your time If you work with telemetry, please check this bulletin board: http://www.bkelly.ws/irig\_106/

                A 1 Reply Last reply
                0
                • B bkelly13

                  Hello, Re:

                  Quote:

                  You may find it easier to run your separate thread as pure procedural code rather than as classes. But that will, of course, depend on what the code is actually doing.

                  I have been thinking about that quite a bit. It would probably be easier to start the process as a single procedure not wrapped up in a class. But, this is for TCP/IP and there is quite a lot to do. I suppose everything could be free standing functions, but that would require a single monster procedure or require a flock of arguments for every call. Being a single person software team where I work has some advantages, but they are truly overwhelmed by the disadvantage of not having anyone to discuss ideas with. I think I will go to a single simple function to test out the concepts and try to get some events working. Then I will return to the TCP/IP part of this. Working one problem area at a time will make this easier. Thank you for your thoughts. EDIT: I have worked this on and off through the day. The current status is that creating a simple thread with some events using a free standing procedure is easier than I thought and easier that it looks. Putting a TCP/IP manager in a single procedure would probably get ugly. Right now my next step is to see what it takes to put this one procedure in a class and start it as a thread. Would this be worth writing up as a series of articles? Article 1: Simple thread, 2: Thread from a class, 3: TCP/IP as a separate thread.

                  Thanks for your time If you work with telemetry, please check this bulletin board: http://www.bkelly.ws/irig\_106/

                  A Offline
                  A Offline
                  Albert Holguin
                  wrote on last edited by
                  #8

                  If you find it helpful, odds are somebody else will as well. With that said, there are a ton of threading and tcp/ip articles, so browse through them to make sure you're not just rewriting an article that's already been written. When you say: "thread from a class", what do you mean? There is an MFC class called CWinThread that allows you to make an entire class that is it's own thread, including the messaging pump required to communicate with it without a separate mutex/critical section (although usually you end up using a combination of messaging and mutexes anyway).

                  B 1 Reply Last reply
                  0
                  • A Albert Holguin

                    If you find it helpful, odds are somebody else will as well. With that said, there are a ton of threading and tcp/ip articles, so browse through them to make sure you're not just rewriting an article that's already been written. When you say: "thread from a class", what do you mean? There is an MFC class called CWinThread that allows you to make an entire class that is it's own thread, including the messaging pump required to communicate with it without a separate mutex/critical section (although usually you end up using a combination of messaging and mutexes anyway).

                    B Offline
                    B Offline
                    bkelly13
                    wrote on last edited by
                    #9

                    I used the phrase of start a thread from a class to indicate that a particular class, such as a TCP/IP manager class, be started as a separate thread from the main app. It turns out there are some difficulties and while relatively simple to execute, I find the code difficult to read. In particular the solutions I found have a difficult to fathom pointer cast and must have a static function used to fire it off. HOWEVER: I just discovered a way to completely bypass that problem. Begin with the class, which of course has a single method, call it main_method() that will loop as needed and not exit until the purpose is complete. Then write a simple free standing procedure. All that procedure does is instantiate the class then call main_method(). It takes one line to instantiate the class and one to call the method. When the method returns, the next line of code deletes the class and one more calls _endthreadex() to formally end the thread. That is really trivial but none of the articles I read about present this concept. (And yes, this completely ignores communications between the thread and the main app, but that is also not so difficult.) Does anyone know of any disadvantage to this?

                    Thanks for your time If you work with telemetry, please check this bulletin board: http://www.bkelly.ws/irig\_106/

                    A 1 Reply Last reply
                    0
                    • B bkelly13

                      I used the phrase of start a thread from a class to indicate that a particular class, such as a TCP/IP manager class, be started as a separate thread from the main app. It turns out there are some difficulties and while relatively simple to execute, I find the code difficult to read. In particular the solutions I found have a difficult to fathom pointer cast and must have a static function used to fire it off. HOWEVER: I just discovered a way to completely bypass that problem. Begin with the class, which of course has a single method, call it main_method() that will loop as needed and not exit until the purpose is complete. Then write a simple free standing procedure. All that procedure does is instantiate the class then call main_method(). It takes one line to instantiate the class and one to call the method. When the method returns, the next line of code deletes the class and one more calls _endthreadex() to formally end the thread. That is really trivial but none of the articles I read about present this concept. (And yes, this completely ignores communications between the thread and the main app, but that is also not so difficult.) Does anyone know of any disadvantage to this?

                      Thanks for your time If you work with telemetry, please check this bulletin board: http://www.bkelly.ws/irig\_106/

                      A Offline
                      A Offline
                      Albert Holguin
                      wrote on last edited by
                      #10

                      There are some simple issues with using _endthreadex() and in a typical worker thread you don't even have to call it explicitly but in any case... I don't quite see why doing all this is beneficial. Maybe if you posted some of the code for reference I could give you some better feedback.

                      B 1 Reply Last reply
                      0
                      • A Albert Holguin

                        There are some simple issues with using _endthreadex() and in a typical worker thread you don't even have to call it explicitly but in any case... I don't quite see why doing all this is beneficial. Maybe if you posted some of the code for reference I could give you some better feedback.

                        B Offline
                        B Offline
                        bkelly13
                        wrote on last edited by
                        #11

                        My application is to process telemetry data and send it to a display device. The band width is high so the TCP/IP manager will be in a separate thread. To my knowledge I have this figured out now. The function that instantiates the class and calls it also calls endthreadex() when the class exits. Quite simple now. But if you say there are issues with using _endthreadex() I would like to hear about them.

                        Thanks for your time If you work with telemetry, please check this bulletin board: http://www.bkelly.ws/irig\_106/

                        A 1 Reply Last reply
                        0
                        • B bkelly13

                          My application is to process telemetry data and send it to a display device. The band width is high so the TCP/IP manager will be in a separate thread. To my knowledge I have this figured out now. The function that instantiates the class and calls it also calls endthreadex() when the class exits. Quite simple now. But if you say there are issues with using _endthreadex() I would like to hear about them.

                          Thanks for your time If you work with telemetry, please check this bulletin board: http://www.bkelly.ws/irig\_106/

                          A Offline
                          A Offline
                          Albert Holguin
                          wrote on last edited by
                          #12

                          Well if anything is waiting on the thread handle, it's going to wait forever (or until it times out) because the thread handle doesn't get dealt with properly, but that would only be an issue if you were waiting on the handle (or if another unsuspecting programmer waits on your thread handle). Typically the proper way of ending a thread is to have it end itself. In the case of a socket handling thread, you can have something to signal an end to the capturing process. If your thread is in a blocking recv() call, closing your socket will trigger a return. From MSDN:

                          Quote:

                          Like the Win32 ExitThread API, _endthreadex does not close the thread handle.

                          1 Reply Last reply
                          0
                          Reply
                          • Reply as topic
                          Log in to reply
                          • Oldest to Newest
                          • Newest to Oldest
                          • Most Votes


                          • Login

                          • Don't have an account? Register

                          • Login or register to search.
                          • First post
                            Last post
                          0
                          • Categories
                          • Recent
                          • Tags
                          • Popular
                          • World
                          • Users
                          • Groups