News:

MASM32 SDK Description, downloads and other helpful links
MASM32.com New Forum Link
masmforum WebSite

Mutex ans Semaphore

Started by Danesh, June 22, 2005, 07:01:50 PM

Previous topic - Next topic

Danesh

Hi,

1. Can anybody tell me whats diffrence between Mutex and Semaphore ?
2. Can anybody send me a sample code creating, signaling and checking status and waiting for a mutex ?

Thanks,

Danesh


Jibz

Mutex @ Wikipedia

Mutex @ MSDN

Semaphore @ Wikipedia

Sepmaphoe @ MSDN

For simple example code, check the 'Using ...' links at the bottom of the MSDN pages.

James Ladd

Danesh,
If you need more information or an example let me know.
Win32 threading is a pet love of mine.
Rgs, striker

Danesh

Hi James,

That would be super great  :U Please send me your samples and also please explain for me whats difference between Semaphore and Mutex. I just guess that mutex is used between threads but semaphore between processes. Am I right ?

Thanks,

Danesh


James Ladd

A mutex provides mutual exclusion to a resource. A win32 critical section is an example of this.
If only one thread or process should change a piece of memory at a time, then you guard it with a mutex.
When you have the mutex you have exclusive control of the item.
You dont actually have exclusive control, you actual just have a mechanism and agreement in your code to
not change the same value at the same time.

A semaphore is similar to a mutext, except that it involves a state of signaled or not signaled.
Typically a thread will wait on a semaphore until it becomes signaled. See CreateEvent as an example
api for creating a semaphore.

A counted semaphore is a semaphore with a signal count. Typically this involves a semaphore and a count.
So if you have a limited resource of say five items, you allow threads to get exclusive control of the item
for upto 5 threads. The 6th thread will block waiting to get access. When one of the other users of the
resource releases it, then the waiting thread will get it.

Hope this helps.

James Ladd

BTW - A great book is Multithreading Applications in Win32 !
You should read this.

Webring

For multi-threading let me give you some advice. In Iczelion's tuts and others i've read on doing multi-threading in asm i've noticed they just toss a "ret" at the end of the procedure thats called in a new thread.And this will cause you unexpected and severe problems, do to thread synchronizing. While  many people recommend using mutexs and even converting threads to semaphone,I've found they're not very efficent, atleast in my case. Instead, I put the following code at the end of my thread procedures, and all works fine  :U

invoke GetCurrentThread
invoke TerminateThread,eax,0