CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 8 of 8
  1. #1
    Join Date
    Feb 2007
    Posts
    149

    How Do I send Parameters to a Thread in Motion?

    Hi


    I am trying to figure out how to pass a parameter to a Thread . Specifically char*. I might not be explaining correctly, so here are some snippets of my code.

    My main looks like this
    Code:
    int main()
    {  
                 ThreadManager tm; 
                 tm.launchThread (&tm); 
                 
                 while(true)
                 {
                        // ... code to capture events and send char* parameters
                       // by some yet to be determined means to this thread.
                 }
    
    } 
    
    //---------------------
    class ThreadManager
    {
         private: 
          DWORD m_dwThreadID; 
          HANDLE m_hThread;           
                  
         public:
           
          ThreadManager(); 
          ~ThreadManager();      
          bool launchThread(ThreadManager *w); 
          HANDLE TheHandle(void) const; 
          static DWORD WINAPI  ThreadFunc(LPVOID pvParam);
          void close();
          void shuttingDown();
    };
    
    implementation below 
    
    ...
    
    DWORD WINAPI ThreadManager::ThreadFunc(LPVOID pvParam)
    {
    
         SpecialThread sp;
         SpecialThread.foo("Sample Parameter");
          while(true)
          {
                    
           }
    }
    I know this might look a bit weird. But it's necessary for me to keep main from being blocked by the activities of SpecialThread sp; It's a long story. That class just takes a couple seconds to do what it does and I can't have it freeze the app. I tried every work around and can't find one. With this solution SpecialThread launches and main() does not get blocked.

    So here is the big question:

    SpecialThread takes char* in foo(char* c );.

    My hope is to figure out a way to pass a char* from main() through Threadmanager to SpecialThread a char* parameter.

    Does anyone have any idea on how I could possibly do this ?
    SpecialThread will be the only thread launched. So If I can just send some char* parameters to foo() I'll be finished.

    Thanks in advance - will definitily be giving rep points for help on this one .

    Stephen
    Last edited by stephenprogrammer07; August 31st, 2007 at 02:34 AM.

  2. #2
    Arjay's Avatar
    Arjay is offline Moderator / EX MS MVP Power Poster
    Join Date
    Aug 2004
    Posts
    13,490

    Re: How Do I send Parameters to a Thread in Motion?

    The following is a snippet from the GG article SimpleThread: Part I and uses the common practice of passing the 'this' pointer to a class containing a static thread proc:

    Code:
    // Create the secondary worker thread - pass the thispointer so we can access the class methods/variables
    HRESULT CreateThread( )
    
    
    {
    // Fire off the thread if( NULL == (m_hThread = (HANDLE)_beginthreadex( NULL , 0 , ThreadProc , static_cast<LPVOID>( this ) , 0 , NULL) ) ) {
    return HRESULT_FROM_WIN32( ::GetLastError( ) );
    } return S_OK;
    } // Thread proc - where the worker thread code happens static UINT WINAPI ThreadProc( LPVOID lpContext ) {
    CProgressMgr* pProgressMgr = reinterpret_cast< CProgressMgr* >( lpContext ); // Loop to simulate a worker operation for( UINT uCount = 0; uCount < 100; uCount++ ) {
    // Check if the shutdown event has been set, // if so exit the thread if( WAIT_OBJECT_0 == WaitForSingleObject( pProgressMgr->GetShutdownEvent( ), 0 ) ) {
    return 1;
    } // Send the progress message to the UI pProgressMgr->NotifyUI( NOTIFY_PROGRESS ); // Sample code - delay the operation a bit Sleep( 75 );
    } // Send the thread completed message to the UI pProgressMgr->NotifyUI( NOTIFY_THREAD_COMPLETED ); return 0;
    }

    Notice the 'this' pointer is passed during thread creation. This allows the worker thread to access the class instance data.

    In your case of the char*, don't forget to synchronize access to the string pointer. You can't have a thread writing to a resource while another thread is reading from the resource without synchronizing access with a cs or mutex.
    Last edited by Arjay; August 31st, 2007 at 09:01 AM.

  3. #3
    Join Date
    Jun 2004
    Location
    India
    Posts
    432

    Re: How Do I send Parameters to a Thread in Motion?

    Passing the this pointer works in some cases.

    For other cases, the easiest, and most straightforward way is to use thread messsage Qs and send windows messages to your worker thread. Remember to implement a thread message loop into your worker thread. Look up on MSDN for an example of thread loop; OR just copy one from MFC generated thread loop. You use PostThreadMessage(...) to send messages to your worker thread and use the two DWORD parameters to pass along the data. If your complete data can fit into those two DWORDs, like sending two integers, then you are done. If you data is longer than that, then you pass along the pointer to that data (making sure that the data itself stays in scope till the time the worker thread is done with it). So you can e.g. pass along that char* p in one of those thread parameters.

    Other ways are more round about way of doing it - implement your own thread communication scheme. e.g. use a global buffer and implement a producer/consumer solution. One thread writes the data into that buffer and the worker thread reads the data off that buffer. Remember to include all the associated synchronization, signalling when the data is there, taking care of buffer full and buffer empty etc. If you read up the producer/consumer problem in any OS book (or internet) you will get a fair idea on what this is all about. Needless to say that in the end you end up implementing a sort of thread Q itself. But this solution has its own uses in some circumstances.
    Say no to supplying ready made code for homework/work assignments!!

    Please rate this post!

  4. #4
    Arjay's Avatar
    Arjay is offline Moderator / EX MS MVP Power Poster
    Join Date
    Aug 2004
    Posts
    13,490

    Re: How Do I send Parameters to a Thread in Motion?

    Underdog, it what situations does PostThreadMessage benefit you over passing a [this] pointer? I've never used the message technique before because it always seemed like overhead that didn't gain me anything. Can you give me an example where PostThreadMessage would work where passing the pointer wouldn't?

  5. #5
    Join Date
    Feb 2002
    Posts
    4,640

    Re: How Do I send Parameters to a Thread in Motion?

    IIRC, using PostThreadMessage really just lets the framework handle all the synchronization, thread access to messages and data, etc. I've never used it myself, preferring to control all the data access myself.

    Viggy

  6. #6
    Join Date
    Jun 2004
    Location
    India
    Posts
    432

    Re: How Do I send Parameters to a Thread in Motion?

    Any type of producer/consumer problem can be neatly solved by using thread messages. Just passing the this pointer works only in cases where the worker thread just munges on some data from the class that it is passed and then it finishes. There are many problems where there are multiple threads that continue to stay on and act on e.g. messages/data being produced by some producer thread. Mostly these cases arise when the threads have to maintain states.
    Say no to supplying ready made code for homework/work assignments!!

    Please rate this post!

  7. #7
    Arjay's Avatar
    Arjay is offline Moderator / EX MS MVP Power Poster
    Join Date
    Aug 2004
    Posts
    13,490

    Re: How Do I send Parameters to a Thread in Motion?

    Quote Originally Posted by UnderDog
    Any type of producer/consumer problem can be neatly solved by using thread messages. Just passing the this pointer works only in cases where the worker thread just munges on some data from the class that it is passed and then it finishes.
    By passing the pointer can't you share pretty much any data between threads? That data can be a list, a queue or whatever. I don't see how you are limited to munging data.
    Quote Originally Posted by UnderDog
    There are many problems where there are multiple threads that continue to stay on and act on e.g. messages/data being produced by some producer thread. Mostly these cases arise when the threads have to maintain states.
    What are these problems? I mean if you can access any data with the pointer (and the data is synchronized) I don't see any issues where moving to PostThreadMessage solves.

  8. #8
    Join Date
    Jun 2004
    Location
    India
    Posts
    432

    Re: How Do I send Parameters to a Thread in Motion?

    You can pass data by passing in pointers to lists or Qs and then can implement your own synchronization mechanisms. That is what I also said as one of the mechanisms. But why would you want to go to the trouble of implementing your own lists and Qs and synchronization etc. when the windows thread Q does similar things? For great many applications windows thread Q might just be appropriate. If e.g. you have one thread that gets all the messages from external world and then parcels them out to say N number of threads, then you can either implement your own data structures to distribute those messages to those threads OR just make use of windows thread message Q.

    What is bad about using windows thread message Qs for passing data? Is it not the precise reason why the thread Qs exist? To pass data to threads? Windows programmers could have implemented it as, pass messages in lists and the list pointers are passed to threads at the startup. In fact that is not much different paradigm at all.

    See the point I am trying to make is that you can do windows GUI programming by directly programming against Win API. But why go to the trouble if MFC would just suit your purpose.
    Say no to supplying ready made code for homework/work assignments!!

    Please rate this post!

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured