Following is a sample code I got from the MSDN help on using the mutex with
multiple threads. I can't figure out how the operating system decides when
the break out of the thread function to allow entry for another thread. It
doesn't appear to be under the control of the code. Is that something the
system determines? based on time slice, perhaps?

#include "stdafx.h"

#include <windows.h>

#include <stdio.h>

#define THREADCOUNT 2

HANDLE ghMutex;

DWORD WINAPI WriteToDatabase( LPVOID );

void main()

{

HANDLE aThread[THREADCOUNT];

DWORD ThreadID;

int i;

// Create a mutex with no initial owner

ghMutex = CreateMutex(

NULL, // default security attributes

FALSE, // initially not owned

NULL); // unnamed mutex

if (ghMutex == NULL)

{

printf("CreateMutex error: %d\n", GetLastError());

return;

}

// Create worker threads

for( i=0; i < THREADCOUNT; i++ )

{

aThread[i] = CreateThread(

NULL, // default security attributes

0, // default stack size

(LPTHREAD_START_ROUTINE) WriteToDatabase,

NULL, // no thread function arguments

0, // default creation flags

&ThreadID); // receive thread identifier

if( aThread[i] == NULL )

{

printf("CreateThread error: %d\n", GetLastError());

return;

}

}

// Wait for all threads to terminate

WaitForMultipleObjects(THREADCOUNT, aThread, TRUE, INFINITE);

// Close thread and mutex handles

for( i=0; i < THREADCOUNT; i++ )

CloseHandle(aThread[i]);

CloseHandle(ghMutex);

}

DWORD WINAPI WriteToDatabase( LPVOID lpParam )

{

DWORD dwCount=0, dwWaitResult;


printf("%d*********************\n", GetCurrentThreadId());

// Request ownership of mutex.

while( dwCount < 20 )

{

printf("%d dwCount = %d\n", GetCurrentThreadId(), (int)dwCount);


printf("%d ...wait...\n", GetCurrentThreadId());

dwWaitResult = WaitForSingleObject(

ghMutex, // handle to mutex

INFINITE); // no time-out interval


printf("%d ---switch---\n", GetCurrentThreadId());

switch (dwWaitResult)

{

// The thread got ownership of the mutex

case WAIT_OBJECT_0:

__try {

// TODO: Write to the database

printf("%d writing to database...\n",

GetCurrentThreadId());

dwCount++;

}

__finally {

// Release ownership of the mutex object

if (! ReleaseMutex(ghMutex))

{

// Deal with error.

}

printf("%d xxxreleasexxx\n", GetCurrentThreadId());

}

break;

// The thread got ownership of an abandoned mutex

case WAIT_ABANDONED:

printf("%dWAIT_ABANDONED------------\n", GetCurrentThreadId());

return FALSE;

}

}

printf("%d----------------------\n", GetCurrentThreadId());

return TRUE;

}

Re: how does system determine when to enter the thread function when using mutex by Igor

Igor
Thu Jul 24 06:45:50 CDT 2008

"Daniel" <newsonly@cableone.net> wrote in message
news:eqVdWBV7IHA.2336@TK2MSFTNGP03.phx.gbl
> Following is a sample code I got from the MSDN help on using the
> mutex with multiple threads. I can't figure out how the operating
> system decides when the break out of the thread function to allow
> entry for another thread.

I don't understand the question. What do you mean, break out of the
thread function? The whole point of threads is that they run
simultaneously, in parallel. The system doesn't need to "break out" of
one to let the other run. The goal of synchronization primitives like
mutexes is to _restrict_ this parallelism (which is sometimes
necessary), not to enable it.

A thread does WaitForSingleObject(ghMutex, INFINITE). Suppose the mutex
is unowned at the moment. In this case, the thread acquires (becomes the
owner of) the mutex, WaitForSingleObject returns, and the thread
proceeds with its work.

Meanwhile, another thread calls WaitForSingleObject on the same mutex.
This time the mutex is owned, so the thread is waiting for it to become
free. WaitForSingleObject simply doesn't return until it happens.

Eventually, first thread calls ReleaseMutex. The mutex is now unowned
again, but there's a thread waiting on it. This thread now acquires the
mutex, its WaitForSingleObject call finally returns, and it proceeds
with its work.
--
With best wishes,
Igor Tandetnik

With sufficient thrust, pigs fly just fine. However, this is not
necessarily a good idea. It is hard to be sure where they are going to
land, and it could be dangerous sitting under them as they fly
overhead. -- RFC 1925



Re: how does system determine when to enter the thread function when using mutex by Daniel

Daniel
Thu Jul 24 07:07:47 CDT 2008

I was running the code in debug mode. I followed the sequence of the code
using the printf statements. In the other examples with multiple threads
the code execution would only change threads during one of the
"WaitForMessage" API functions or at the end of the callback function. This
example would change threads right in the middle of a set of statements and
not during a "WaitForMessage" function. Perhaps you should try that code
out to see.

Daniel

"Igor Tandetnik" <itandetnik@mvps.org> wrote in message
news:OHm9ULY7IHA.5440@TK2MSFTNGP02.phx.gbl...
> "Daniel" <newsonly@cableone.net> wrote in message
> news:eqVdWBV7IHA.2336@TK2MSFTNGP03.phx.gbl
>> Following is a sample code I got from the MSDN help on using the
>> mutex with multiple threads. I can't figure out how the operating
>> system decides when the break out of the thread function to allow
>> entry for another thread.
>
> I don't understand the question. What do you mean, break out of the thread
> function? The whole point of threads is that they run simultaneously, in
> parallel. The system doesn't need to "break out" of one to let the other
> run. The goal of synchronization primitives like mutexes is to _restrict_
> this parallelism (which is sometimes necessary), not to enable it.
>
> A thread does WaitForSingleObject(ghMutex, INFINITE). Suppose the mutex is
> unowned at the moment. In this case, the thread acquires (becomes the
> owner of) the mutex, WaitForSingleObject returns, and the thread proceeds
> with its work.
>
> Meanwhile, another thread calls WaitForSingleObject on the same mutex.
> This time the mutex is owned, so the thread is waiting for it to become
> free. WaitForSingleObject simply doesn't return until it happens.
>
> Eventually, first thread calls ReleaseMutex. The mutex is now unowned
> again, but there's a thread waiting on it. This thread now acquires the
> mutex, its WaitForSingleObject call finally returns, and it proceeds with
> its work.
> --
> With best wishes,
> Igor Tandetnik
>
> With sufficient thrust, pigs fly just fine. However, this is not
> necessarily a good idea. It is hard to be sure where they are going to
> land, and it could be dangerous sitting under them as they fly
> overhead. -- RFC 1925
>



Re: how does system determine when to enter the thread function when using mutex by Igor

Igor
Thu Jul 24 07:24:30 CDT 2008

"Daniel" <newsonly@cableone.net> wrote in message
news:u5D9jXY7IHA.2072@TK2MSFTNGP04.phx.gbl
> I was running the code in debug mode. I followed the sequence of the
> code using the printf statements. In the other examples with
> multiple threads the code execution would only change threads during
> one of the "WaitForMessage" API functions

If it happened, it was just by accident. Don't extrapolate your
observations in a particular case to a general rule. Unless explicitly
synchronized, threads can run in any order, interleaved, and on
multi-CPU machines truly simultaneously.

> This example would change threads right in the
> middle of a set of statements and not during a "WaitForMessage"
> function.

There's nothing wrong with that. printf statements that are outside the
section of code protected by the mutex can and will interleave. You use
a mutex precisely to prevent that. Note how the statements that are
inside the mutex are never interleaved:

printf("%d ---switch---\n", ...);
printf("%d writing to database...\n", ...);

You should never see "switch" message from one thread followed by
"switch" from another, without an intervening "writing to database" from
the first.
--
With best wishes,
Igor Tandetnik

With sufficient thrust, pigs fly just fine. However, this is not
necessarily a good idea. It is hard to be sure where they are going to
land, and it could be dangerous sitting under them as they fly
overhead. -- RFC 1925



Re: how does system determine when to enter the thread function when by David

David
Thu Jul 24 07:40:26 CDT 2008

Daniel wrote:
> I was running the code in debug mode. I followed the sequence of the code
> using the printf statements. In the other examples with multiple threads
> the code execution would only change threads during one of the
> "WaitForMessage" API functions or at the end of the callback function. This
> example would change threads right in the middle of a set of statements and
> not during a "WaitForMessage" function. Perhaps you should try that code
> out to see.

Daniel:

This is the nature of multi-threading. The OS determines when to halt one thread
and start another (and to which processor to assign threads on a multi-processor
(or multi-core) machine). This switching is *not* controlled from inside your code.

Ideally, a multi-threaded application should not require mutex's and other
synchronization techniques. As Joe Newcomer says: The best synchronization is no
synchronization.

--
David Wilkinson
Visual C++ MVP

Re: how does system determine when to enter the thread function when using mutex by Daniel

Daniel
Thu Jul 24 12:08:36 CDT 2008

ok. Thanks. That was helpful. That's a good word for it . . .
"interleaved".

Daniel

"Igor Tandetnik" <itandetnik@mvps.org> wrote in message
news:uNfX7gY7IHA.4112@TK2MSFTNGP05.phx.gbl...
> "Daniel" <newsonly@cableone.net> wrote in message
> news:u5D9jXY7IHA.2072@TK2MSFTNGP04.phx.gbl
>> I was running the code in debug mode. I followed the sequence of the
>> code using the printf statements. In the other examples with
>> multiple threads the code execution would only change threads during
>> one of the "WaitForMessage" API functions
>
> If it happened, it was just by accident. Don't extrapolate your
> observations in a particular case to a general rule. Unless explicitly
> synchronized, threads can run in any order, interleaved, and on multi-CPU
> machines truly simultaneously.
>
>> This example would change threads right in the
>> middle of a set of statements and not during a "WaitForMessage"
>> function.
>
> There's nothing wrong with that. printf statements that are outside the
> section of code protected by the mutex can and will interleave. You use a
> mutex precisely to prevent that. Note how the statements that are inside
> the mutex are never interleaved:
>
> printf("%d ---switch---\n", ...);
> printf("%d writing to database...\n", ...);
>
> You should never see "switch" message from one thread followed by "switch"
> from another, without an intervening "writing to database" from the first.
> --
> With best wishes,
> Igor Tandetnik
>
> With sufficient thrust, pigs fly just fine. However, this is not
> necessarily a good idea. It is hard to be sure where they are going to
> land, and it could be dangerous sitting under them as they fly
> overhead. -- RFC 1925
>