Thread: multithreading in c

  1. #1
    Registered User
    Join Date
    Jul 2007
    Posts
    9

    Smile multithreading in c

    Dear all,
    I am trying to write a software in c Language which do two tasks at the same time.
    It first function is initializing a socket in windows and listing for incoming connection,
    Second function is monitoring hardware output connected to the COM 1 and if he got something it should write to a file. Both should happen same time.

    If a user connected then to the listing socket he will get the report of lst 10 events of the file which is updated by the COM monitor and write function.

    Second function is fully independent from first function.

    I have coded the both functions separately, tested, and working well. When I run function 1(listing for incoming connection) function 2 is remain stop mode. If func 2 runs fun 1 remain stop mode. (procedural programming)

    I need to do this both run in same time using threads or processes in a one programme (one executable file).

    Can I do this with threads?

    I have tried so many ways to find this. Msdn also not giving good reference to me to do this.

    If Some one knows well pls help me to do this - guide me the way fo doing this in th coding. I am expecting a well described answer form you all.


    func1() --network listing
    func2() --monitoring com1 and updating file.

    Then how can I code a Programme to do both in independently without exiting each other?????



    Thebrighter

  2. #2
    Deathray Engineer MacGyver's Avatar
    Join Date
    Mar 2007
    Posts
    3,210
    Yes, use threads. I'm writing this from memory, but I think you have two main ways of doing this in a Windows-specific way:

    • The _beginthread() way.
    • The CreateThread() way.


    There might exist variations on those functions (ie. CreateThreadex() or something), and there are separate ways to end threads for each of those methods. Do NOT mix them up.

    If you're already familliar with pthreads for *nix system, then there should be a port of pthreads for Windows somewhere around that people have posted here before. That will take care of calling the Windows-specific functions, and it will make your threading slightly more portable (although I'm not sure how portable reading from COM 1 is, so perhaps this is pointless. )

  3. #3
    Registered User
    Join Date
    Jul 2007
    Posts
    9

    Smile

    Thnaks for your reply. When I am searching I have found this sample code.

    Code:
    
    void ThreadProc1(void *param);
    void ThreadProc2(void *param);
    
    int main()
    {
        int val = 0;
        HANDLE handle;
    
        val=1;
        handle = (HANDLE) _beginthread( ThreadProc1,0,&val); // create thread
        WaitForSingleObject(handle,INFINITE);
        
        val=2;
        handle = (HANDLE) _beginthread( ThreadProc1,0,&val); // create thread
        WaitForSingleObject(handle,INFINITE);
    
    
        return 0;
    }
    
    
    void ThreadProc1(void *param)
    {
        int h=*((int*)param);
        functin1();
        _endthread();
    }
    
    void ThreadProc2(void *param)
    {
        int h=*((int*)param);
        functin2();
        _endthread();
    }
    In here each thread start after finishing previous thread.
    Can I know the way of insert my two functions to this to work in fully independent way of working my functions.?

    Thebrighter
    Last edited by thebrighter; 07-10-2007 at 06:03 AM.

  4. #4
    Deathray Engineer MacGyver's Avatar
    Join Date
    Mar 2007
    Posts
    3,210
    Should either of your two functions return before the other? Is there a chance either of your functions will return early? Do you want the program to wait for both of them? What are the prototypes for your two functions?

    Consider using _beginthread() or _beginthreadex(), and calling WaitForMultipleObjects() after starting them.

  5. #5
    Captain - Lover of the C
    Join Date
    May 2005
    Posts
    341
    Code:
    WaitForSingleObject(handle,INFINITE);
    This line waits for "handle" to close before continuing. If you remove this line, it will go straight to creating the next thread. You're going to want more than one handle:
    Code:
    HANDLE handle1, handle2;
    Also, look into CloseHandle(). I believe you're supposed to make a call to it from the main thread as a clean up of the other threads.
    Don't quote me on that... ...seriously

  6. #6
    Deathray Engineer MacGyver's Avatar
    Join Date
    Mar 2007
    Posts
    3,210
    Quote Originally Posted by Brad0407 View Post
    Also, look into CloseHandle(). I believe you're supposed to make a call to it from the main thread as a clean up of the other threads.
    OK, I managed to mix myself up a bit, so I was wrong to say you could use _beginthread() and WaitForMultipleObjects().

    Here are some rules with regard to Windows multithreading applications using the Windows API:

    • Do not call CloseHandle() if you use _beginthread(). _endthread() does this automatically. If you use _beginthreadex(), then yes, you'll need to end the thread yourself from the caller.

      _endthread automatically closes the thread handle (whereas _endthreadex does not). Therefore, when using _beginthread and _endthread, do not explicitly close the thread handle by calling the Win32 CloseHandle API. This behavior differs from the Win32 ExitThread API.
      http://msdn2.microsoft.com/en-us/lib...cb(VS.80).aspx
    • You cannot wait on a thread with WaitForSingleObject() that has been created with _beginthread() because the thread will be destroyed and the HANDLE closed with _endthread().

      The following sample code demonstrates how you can use the thread handle returned by _beginthreadex with the synchronization API WaitForSingleObject. The main thread waits for the second thread to terminate before it continues. When the second thread calls _endthreadex, it causes its thread object to go to the signaled state. This allows the primary thread to continue running. This cannot be done with _beginthread and _endthread, because _endthread calls CloseHandle, destroying the thread object before it can be set to the signaled state.


    I would suggest _beginthreadex() plus WaitForMultipleObjects() personally without knowing anything else to do with his code. If he doesn't use the C library, he should consider using CreateThread(). If he does use the C library at all, he's in danger of causing resource leaks if he uses CreateThread():

    A thread in an executable that calls the C run-time library (CRT) should use the _beginthreadex and _endthreadex functions for thread management rather than CreateThread and ExitThread; this requires the use of the multi-threaded version of the CRT. If a thread created using CreateThread calls the CRT, the CRT may terminate the process in low-memory conditions.
    http://msdn2.microsoft.com/en-us/library/ms682453.aspx

  7. #7
    Registered User
    Join Date
    Jul 2007
    Posts
    9

    Smile

    I have edited the code. Pls tell me is it the correct one

    Code:
    void ThreadProc1(void *param);
    void ThreadProc2(void *param);
    
    int main()
    {
        int val = 0;
        HANDLE handle1,handle2;
    
        val=1;
        handle1 = (HANDLE) _beginthread( ThreadProc1,0,&val); // create thread
            
        val=2;
        handle2= (HANDLE) _beginthread( ThreadProc2,0,&val); // create thread
        
        return 0;
    }
    
    
    void ThreadProc1(void *param)
    {
        int h=*((int*)param);
        functin1();
        _endthread();
    }
    
    void ThreadProc2(void *param)
    {
        int h=*((int*)param);
        functin2();
        _endthread();
    }

  8. #8
    Deathray Engineer MacGyver's Avatar
    Join Date
    Mar 2007
    Posts
    3,210
    If you're not going to use param in either function, don't waste time passing something to the thread procedure and then casting it. That's pointless.

    Your main() thread will just exit, and I believe kill off the other threads. If you're not going to wait for the threads, why not just execute one of the functions in your main thread? Try something like this:

    Code:
    void ThreadProc1(void *param);
    
    int main()
    {
        int val = 0;
        HANDLE handle1;
    
        _beginthread( ThreadProc1,0,NULL);
        function2();
        
        return 0;
    }
    
    
    void ThreadProc1(void *param)
    {
        functin1();
        _endthread();
    }
    The program will exit when function2() is finished. I'm not sure how safe this really is in terms of what resources might be lost if Thread 1 is still running. You should consider waiting for it anyway.

  9. #9
    Hurry Slowly vart's Avatar
    Join Date
    Oct 2006
    Location
    Rishon LeZion, Israel
    Posts
    6,788
    Note that

    It is safer to use _beginthreadex than _beginthread. If the thread generated by _beginthread exits quickly, the handle returned to the caller of _beginthread might be invalid or, worse, point to another thread. However, the handle returned by _beginthreadex has to be closed by the caller of _beginthreadex, so it is guaranteed to be a valid handle if _beginthreadex did not return an error.
    http://msdn2.microsoft.com/en-us/lib...cb(VS.80).aspx
    All problems in computer science can be solved by another level of indirection,
    except for the problem of too many layers of indirection.
    – David J. Wheeler

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Multithreading (flag stopping a thread, ring buffer) volatile
    By ShwangShwing in forum C Programming
    Replies: 3
    Last Post: 05-19-2009, 07:27 AM
  2. multithreading in C++
    By manzoor in forum C++ Programming
    Replies: 19
    Last Post: 11-28-2008, 12:20 PM
  3. Question on Multithreading
    By ronan_40060 in forum C Programming
    Replies: 1
    Last Post: 08-23-2006, 07:58 AM
  4. Client/Server and Multithreading
    By osal in forum Windows Programming
    Replies: 2
    Last Post: 07-17-2004, 03:53 AM
  5. Multithreading
    By JaWiB in forum Game Programming
    Replies: 7
    Last Post: 08-24-2003, 09:28 PM