Link to home
Start Free TrialLog in
Avatar of nikhilh
nikhilh

asked on

Synchronisation of Threads in VC++

I am creating threads using API calls. So I cannot use the seamophores class using MFC.

So is there any way of synchronising the threads. I have few global variables which are being accessed by two or more threads. So how do I synchronise them.

Thanks in advance

nikhilh

ASKER CERTIFIED SOLUTION
Avatar of chensu
chensu
Flag of Canada image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of nietod
nietod

That is MFC, though.

You can use CreateMutex() to create mutexes, CreateSemaphore() to create semaphores, and CreateEvent(0 to create events.  These are all regulat API calls.

Oh I see.  chensu interpretted this as an MFC program that doesn't use MFC to create threads.  I interpretted it as a non-MFC program.  Which is right?
Critical sections are much more efficient than mutexes and have similar functionality.

APIs:
  InitializeCriticalSection()
  EnterCriticalSection()
  LeaveCriticalSection()
  DeleteCriticalSection()

MFC object: CCriticalSection
  CCriticalSection() - Constructs a CCriticalSection object.
  Unlock() - Releases the CCriticalSection object.
  Lock() - Use to gain access to the CCriticalSection object.

Tell me it it helps.
Do you know for a fact that they are more efficient?  I always assumed they were implimented using mutexes.
Yes, I do know that for a fact.

A CS only works between threads of a single process so no kernel call (ring 3 --> ring 0 --> ring 3 transition) needs to be made if the CS is free.

I once did an emphirical timing and, if I remember correctly, CS calls were about 20x faster than mutex calls with no blocking (timing with blocking is all but meaningless).

References:
http://www.dejanews.com/dnquery.xp?search=thread&recnum=%3c337b4b70.83813086@neptune%3e%231/1
http://www.dejanews.com/dnquery.xp?search=thread&recnum=%3c34983a37.166416534@news.netvision.net.il%3e%231/1
alexo:
Any data on Events, Semaphores, etc?  I assume that these are in the same category as CS, wrt speed.
>> I assume that these are in the same category as CS, wrt speed.
Same order of magnitude as *mutexes*.  Don't remember the exact details but the results were pretty close.  CSs are much faster because you avoid the kernell call that you must take when working with "real" sync. objects (those you can pass to WaitFor...() APIs).