Question about Threads in C

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • kreagan
    New Member
    • Aug 2007
    • 153

    Question about Threads in C

    I have software for a BERT that networks with a external database (SMU). The program requests information from the SMU and waits for a response. Sometimes, the software hangs while waiting for the information.

    To prevent the program from hanging, I decided to create a threading system such that a timer will indicate if the read procedure is hung. If this is so, the program will have to cancel the read and perform some analysis.

    I decided that the program will spawn a thread to perform the IO. Then start a timer for a period of time. Once the thread is done, it will terminate. If the thread still exists, the program will terminate it and the program will behave accordingly.

    I need some advice as to what to consider. I'm not very skilled with threads since I don't have much applied knowledge. I read that I should use KLT to prevent the whole program from being blocked. So how will my program know if its thread has finished? Should I have flags inside the IO thread that indicate if read happened or not? Should I have two threads, one for keeping the time and one for reading? Then should the program should check if expired flag is set or the read flag is set and behave accordingly?

    Sorry if this question is confusing. I know the outcome I want but have so many ideas to obtain it without the wisdom of what is acheivable.
  • Cucumber
    New Member
    • Sep 2007
    • 90

    #2
    I think using a timer and some flags is a good way to achieve what you want.

    If you are using Win32, the timer could be set in the user interface thread so the operating system can send you WM_TIMER messages. You catch them and check for the flag values.

    The most basic thing to be aware when using threads is concurrent access.

    Concurrent access happens when one thread is setting the value of some variable, i.e. a flag, while another thread is trying to read the value of the same variable, i.e. the same flag. Nasty things can happen as one thread reads the value of the variable while another is changing its value!

    So what you do is using some kind of concurrent access protection functions.

    If using Win32, you can use a "critical section". It is basically an structure you must initialize, and after that you can use it everywhere to protect variables:

    Code:
    ....
    bool flag=true; // global variable
    CRITICAL_SECTION foo; // global variable
    ...
    InitializeCriticalSection(&foo);
    ...
    //at main thread:
    EnterCriticalSection(&foo);
    if( flag )
      // act accordingly
    LeaveCriticalSection(&foo);
    ...
    //at worker thread
    EnterCriticalSection(&foo);
    if( whatever )
       flag = false;
    LeaveCriticalSection(&foo);

    Comment

    Working...