?
Solved

Critical Section implementation in C

Posted on 2003-03-19
9
Medium Priority
?
2,297 Views
Last Modified: 2007-12-19
Hello sharks!

I'm trying to implement the following code in C (not C++) with threads and CS.
For some reason, it seems it does not affect the threads and they all enter the CS.
The app is Win32 based using MS-Visual.
I know this implementation might cause starvation, but i don't care at the moment.. ;)

Please help..



// the paseudo code:

static int cs = 0;

void main()
{
   // run some threads...
}

void thread()
{
   if (cs == 1)
      while(cs);
   cs = 1;

   // do CS here..

   cs = 0;
}
0
Comment
Question by:ben-gur
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 3
  • 3
  • 2
  • +1
9 Comments
 
LVL 1

Expert Comment

by:codez80
ID: 8166067
well first things first. what u r doing is called spinning which basically eats cpu!

add a Sleep(0) statement to give time to other threads to solve that.

second change your decl of int cs to "static volatile int" to avoid optimisation you do not want to help with synchronisation.

good luck

codez80
0
 
LVL 22

Expert Comment

by:grg99
ID: 8166225
Well, you're theoretically fubarred... You could get a thread switch between the test "cs==1" and the set "cs = 1";
It won't happen often, but it WILL happen.

You could do somewhat better with something paranoid like:

cs++;
while( cs > 1 ) {  sleep( 0 ); /* two of us got the lock!! */ }

... do the critical stuff...

cs--;





But that STILL has a small hole- you could BOTH get the lock, then both spin waiting for the other guy to finish..  


to do it the RIGHT way:

You need an atomic test-and-set operation, something which can't be guaranteed in "pure" C.

Try using some of the Windows API for semaphores..  I don't remember what it's called, but it exists.  IIRC on Windows/98 it is a very efficient 2-instruction routine.




0
 
LVL 19

Accepted Solution

by:
mrwad99 earned 280 total points
ID: 8166299
It may help your thinking when it comes to critical sectionsto look at this small piece of code.

Basically this program has one thread updating values in a global array and the main thread outputting the contents of the array.  

If the main thread interrupts the worker thread before it has finished updating *all* of the elements in the array, then the main thread will output values that are not all the same (obviously).  

However the use of the CS ensures that the worker thread finishes updating all of the elements in the array *before* the main thread can output them.

This can be adopted for your purposes with multiple threads easily enough.

If you need more flexibility than given here you may need to consider semaphores as mentioned earlier.

#include <windows.h>
#include <process.h>
#include <stdio.h>

CRITICAL_SECTION cs;

int a[5];

void Thread(void* pParams)
{
     int i, num = 0;
     
    while (1) {
          EnterCriticalSection( &cs );
          printf("In the thread process, num is %i\n", num);
          for (i = 0; i < 5; i++) {
               a[i] = num;
          }
          num++;
          LeaveCriticalSection( &cs );
         
    }
}

int main(void)
{
     InitializeCriticalSection( &cs );

     _beginthread(Thread, 0, NULL);
     while(1) {
          EnterCriticalSection( &cs );
          printf("In the main process\n");
        printf("%d %d %d %d %d\n",  a[0], a[1], a[2], a[3], a[4] );
        LeaveCriticalSection( &cs );
     }
     return 0;
}
 
0
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 4

Author Comment

by:ben-gur
ID: 8166525
Thank you all for your replies. It was very helpful.

Adam Ben-Gur.
0
 
LVL 4

Author Comment

by:ben-gur
ID: 8166527
Thanks man!
0
 
LVL 19

Expert Comment

by:mrwad99
ID: 8166559
Glad to help !
0
 
LVL 1

Expert Comment

by:codez80
ID: 8166683
I THOUGHT YOU WERE GOING TO IMPLEMENT CRITICAL SECTION YOURSELF RATHER THAN RELYING ON WIN32 APIs!!!

codez80
0
 
LVL 4

Author Comment

by:ben-gur
ID: 8166781
Hey codez80,

No need to shout..
I tried to implement it myself because i was unable to use the build-in methods due to C++/C conventions (and also I was probably implementing it wrong..).
I also tried your solution but it seems it didn't work - the threads were still accessing CS at the same time.. (Still don't know why).

Anyhow, the example mrwad99 posted solved the problem, and now it seems everything is running smoothly.

I'm sorry you didn't got the points, but I can choose only one.. Thanks for your time and help man.

Adam.
0
 
LVL 19

Expert Comment

by:mrwad99
ID: 8180818
As a further note ben-gur it is generally better to use
_beginthreadex as opposed to _beginthread for a mulitude of reasons.

The example I posted here is adequate for _beginthread use as there is no explicit closing of the thread which is where the problem with _beginthread lies.

You can find out more about this function by using google or another popular search engine.

:D
0

Featured Post

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

An Outlet in Cocoa is a persistent reference to a GUI control; it connects a property (a variable) to a control.  For example, it is common to create an Outlet for the text field GUI control and change the text that appears in this field via that Ou…
Examines three attack vectors, specifically, the different types of malware used in malicious attacks, web application attacks, and finally, network based attacks.  Concludes by examining the means of securing and protecting critical systems and inf…
The goal of this video is to provide viewers with basic examples to understand opening and writing to files in the C programming language.
The goal of this video is to provide viewers with basic examples to understand opening and reading files in the C programming language.
Suggested Courses
Course of the Month9 days, 3 hours left to enroll

764 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question