473,326 Members | 2,588 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,326 software developers and data experts.

thread synchronization

i have an array that i want all threads to be able to READ from
concurrently, however, at times i want to UPDATE the array. at which point i
want all threads that use it to block when they try to read from the array.
currently i do this by wrapping ALL READ AND WRITE access to the array in a
lock("foobar"){} this prevernts threads from reading from the array while it
is being written to however it ALSO keeps more then one thread from reading
the array at a time. how to solve this so that multiple threads can read the
array at the same time but whent he array is being updated all threads that
want to read from it block until it updates, and so that the code to update
the array blocks until no thread is reading from the array before it starts
to update it?
Nov 17 '05 #1
6 2255
Use a Mutex object,

You can use a mutex object to protect a shared resource from
simultaneous access by multiple threads or processes. The state of a
mutex object is either set to signaled, when it is not owned by any
thread, or nonsignaled, when it is owned. Only one thread at a time can
own a mutex object. For example, to prevent two threads from writing to
shared memory at the same time, each thread waits for ownership of a
mutex object before executing the code that accesses the memory. After
writing to the shared memory, the thread releases the mutex object.

This example demonstrates how to use the classes Mutex, AutoResetEvent,
and WaitHandle in processing threads. It also demonstrates the methods
used in processing the mutex object.

// Mutex.cs
// Mutex object example
using System;
using System.Threading;

public class MutexSample
{
static Mutex gM1;
static Mutex gM2;
const int ITERS = 100;
static AutoResetEvent Event1 = new AutoResetEvent(false);
static AutoResetEvent Event2 = new AutoResetEvent(false);
static AutoResetEvent Event3 = new AutoResetEvent(false);
static AutoResetEvent Event4 = new AutoResetEvent(false);

public static void Main(String[] args)
{
Console.WriteLine("Mutex Sample ...");
// Create Mutex initialOwned, with name of "MyMutex".
gM1 = new Mutex(true,"MyMutex");
// Create Mutex initialOwned, with no name.
gM2 = new Mutex(true);
Console.WriteLine(" - Main Owns gM1 and gM2");

AutoResetEvent[] evs = new AutoResetEvent[4];
evs[0] = Event1; // Event for t1
evs[1] = Event2; // Event for t2
evs[2] = Event3; // Event for t3
evs[3] = Event4; // Event for t4

MutexSample tm = new MutexSample( );
Thread t1 = new Thread(new ThreadStart(tm.t1Start));
Thread t2 = new Thread(new ThreadStart(tm.t2Start));
Thread t3 = new Thread(new ThreadStart(tm.t3Start));
Thread t4 = new Thread(new ThreadStart(tm.t4Start));
t1.Start( ); // Does Mutex.WaitAll(Mutex[] of gM1 and gM2)
t2.Start( ); // Does Mutex.WaitOne(Mutex gM1)
t3.Start( ); // Does Mutex.WaitAny(Mutex[] of gM1 and gM2)
t4.Start( ); // Does Mutex.WaitOne(Mutex gM2)

Thread.Sleep(2000);
Console.WriteLine(" - Main releases gM1");
gM1.ReleaseMutex( ); // t2 and t3 will end and signal

Thread.Sleep(1000);
Console.WriteLine(" - Main releases gM2");
gM2.ReleaseMutex( ); // t1 and t4 will end and signal

// Waiting until all four threads signal that they are done.
WaitHandle.WaitAll(evs);
Console.WriteLine("... Mutex Sample");
}

public void t1Start( )
{
Console.WriteLine("t1Start started, Mutex.WaitAll(Mutex[])");
Mutex[] gMs = new Mutex[2];
gMs[0] = gM1; // Create and load an array of Mutex for WaitAll call
gMs[1] = gM2;
Mutex.WaitAll(gMs); // Waits until both gM1 and gM2 are released
Thread.Sleep(2000);
Console.WriteLine("t1Start finished, Mutex.WaitAll(Mutex[])
satisfied");
Event1.Set( ); // AutoResetEvent.Set() flagging method is done
}

public void t2Start( )
{
Console.WriteLine("t2Start started, gM1.WaitOne( )");
gM1.WaitOne( ); // Waits until Mutex gM1 is released
Console.WriteLine("t2Start finished, gM1.WaitOne( ) satisfied");
Event2.Set( ); // AutoResetEvent.Set() flagging method is done
}

public void t3Start( )
{
Console.WriteLine("t3Start started, Mutex.WaitAny(Mutex[])");
Mutex[] gMs = new Mutex[2];
gMs[0] = gM1; // Create and load an array of Mutex for WaitAny call
gMs[1] = gM2;
Mutex.WaitAny(gMs); // Waits until either Mutex is released
Console.WriteLine("t3Start finished, Mutex.WaitAny(Mutex[])");
Event3.Set( ); // AutoResetEvent.Set() flagging method is done
}

public void t4Start( )
{
Console.WriteLine("t4Start started, gM2.WaitOne( )");
gM2.WaitOne( ); // Waits until Mutex gM2 is released
Console.WriteLine("t4Start finished, gM2.WaitOne( )");
Event4.Set( ); // AutoResetEvent.Set() flagging method is done
}
}

Sample Output

Mutex Sample ...
- Main Owns gM1 and gM2
t1Start started, Mutex.WaitAll(Mutex[])
t2Start started, gM1.WaitOne( )
t3Start started, Mutex.WaitAny(Mutex[])
t4Start started, gM2.WaitOne( )
- Main releases gM1
t2Start finished, gM1.WaitOne( ) satisfied
t3Start finished, Mutex.WaitAny(Mutex[])
- Main releases gM2
t1Start finished, Mutex.WaitAll(Mutex[]) satisfied
t4Start finished, gM2.WaitOne( )
.... Mutex Sample

~~~
Daniel wrote:
i have an array that i want all threads to be able to READ from
concurrently, however, at times i want to UPDATE the array. at which point i
want all threads that use it to block when they try to read from the array.
currently i do this by wrapping ALL READ AND WRITE access to the array in a
lock("foobar"){} this prevernts threads from reading from the array while it
is being written to however it ALSO keeps more then one thread from reading
the array at a time. how to solve this so that multiple threads can read the
array at the same time but whent he array is being updated all threads that
want to read from it block until it updates, and so that the code to update
the array blocks until no thread is reading from the array before it starts
to update it?

Nov 17 '05 #2
Use a Mutex object,

You can use a mutex object to protect a shared resource from
simultaneous access by multiple threads or processes. The state of a
mutex object is either set to signaled, when it is not owned by any
thread, or nonsignaled, when it is owned. Only one thread at a time can
own a mutex object. For example, to prevent two threads from writing to
shared memory at the same time, each thread waits for ownership of a
mutex object before executing the code that accesses the memory. After
writing to the shared memory, the thread releases the mutex object.

This example demonstrates how to use the classes Mutex, AutoResetEvent,
and WaitHandle in processing threads. It also demonstrates the methods
used in processing the mutex object.

// Mutex.cs
// Mutex object example
using System;
using System.Threading;

public class MutexSample
{
static Mutex gM1;
static Mutex gM2;
const int ITERS = 100;
static AutoResetEvent Event1 = new AutoResetEvent(false);
static AutoResetEvent Event2 = new AutoResetEvent(false);
static AutoResetEvent Event3 = new AutoResetEvent(false);
static AutoResetEvent Event4 = new AutoResetEvent(false);

public static void Main(String[] args)
{
Console.WriteLine("Mutex Sample ...");
// Create Mutex initialOwned, with name of "MyMutex".
gM1 = new Mutex(true,"MyMutex");
// Create Mutex initialOwned, with no name.
gM2 = new Mutex(true);
Console.WriteLine(" - Main Owns gM1 and gM2");

AutoResetEvent[] evs = new AutoResetEvent[4];
evs[0] = Event1; // Event for t1
evs[1] = Event2; // Event for t2
evs[2] = Event3; // Event for t3
evs[3] = Event4; // Event for t4

MutexSample tm = new MutexSample( );
Thread t1 = new Thread(new ThreadStart(tm.t1Start));
Thread t2 = new Thread(new ThreadStart(tm.t2Start));
Thread t3 = new Thread(new ThreadStart(tm.t3Start));
Thread t4 = new Thread(new ThreadStart(tm.t4Start));
t1.Start( ); // Does Mutex.WaitAll(Mutex[] of gM1 and gM2)
t2.Start( ); // Does Mutex.WaitOne(Mutex gM1)
t3.Start( ); // Does Mutex.WaitAny(Mutex[] of gM1 and gM2)
t4.Start( ); // Does Mutex.WaitOne(Mutex gM2)

Thread.Sleep(2000);
Console.WriteLine(" - Main releases gM1");
gM1.ReleaseMutex( ); // t2 and t3 will end and signal

Thread.Sleep(1000);
Console.WriteLine(" - Main releases gM2");
gM2.ReleaseMutex( ); // t1 and t4 will end and signal

// Waiting until all four threads signal that they are done.
WaitHandle.WaitAll(evs);
Console.WriteLine("... Mutex Sample");
}

public void t1Start( )
{
Console.WriteLine("t1Start started, Mutex.WaitAll(Mutex[])");
Mutex[] gMs = new Mutex[2];
gMs[0] = gM1; // Create and load an array of Mutex for WaitAll call
gMs[1] = gM2;
Mutex.WaitAll(gMs); // Waits until both gM1 and gM2 are released
Thread.Sleep(2000);
Console.WriteLine("t1Start finished, Mutex.WaitAll(Mutex[])
satisfied");
Event1.Set( ); // AutoResetEvent.Set() flagging method is done
}

public void t2Start( )
{
Console.WriteLine("t2Start started, gM1.WaitOne( )");
gM1.WaitOne( ); // Waits until Mutex gM1 is released
Console.WriteLine("t2Start finished, gM1.WaitOne( ) satisfied");
Event2.Set( ); // AutoResetEvent.Set() flagging method is done
}

public void t3Start( )
{
Console.WriteLine("t3Start started, Mutex.WaitAny(Mutex[])");
Mutex[] gMs = new Mutex[2];
gMs[0] = gM1; // Create and load an array of Mutex for WaitAny call
gMs[1] = gM2;
Mutex.WaitAny(gMs); // Waits until either Mutex is released
Console.WriteLine("t3Start finished, Mutex.WaitAny(Mutex[])");
Event3.Set( ); // AutoResetEvent.Set() flagging method is done
}

public void t4Start( )
{
Console.WriteLine("t4Start started, gM2.WaitOne( )");
gM2.WaitOne( ); // Waits until Mutex gM2 is released
Console.WriteLine("t4Start finished, gM2.WaitOne( )");
Event4.Set( ); // AutoResetEvent.Set() flagging method is done
}
}

Sample Output

Mutex Sample ...
- Main Owns gM1 and gM2
t1Start started, Mutex.WaitAll(Mutex[])
t2Start started, gM1.WaitOne( )
t3Start started, Mutex.WaitAny(Mutex[])
t4Start started, gM2.WaitOne( )
- Main releases gM1
t2Start finished, gM1.WaitOne( ) satisfied
t3Start finished, Mutex.WaitAny(Mutex[])
- Main releases gM2
t1Start finished, Mutex.WaitAll(Mutex[]) satisfied
t4Start finished, gM2.WaitOne( )
.... Mutex Sample

~~~
Daniel wrote:
i have an array that i want all threads to be able to READ from
concurrently, however, at times i want to UPDATE the array. at which point i
want all threads that use it to block when they try to read from the array.
currently i do this by wrapping ALL READ AND WRITE access to the array in a
lock("foobar"){} this prevernts threads from reading from the array while it
is being written to however it ALSO keeps more then one thread from reading
the array at a time. how to solve this so that multiple threads can read the
array at the same time but whent he array is being updated all threads that
want to read from it block until it updates, and so that the code to update
the array blocks until no thread is reading from the array before it starts
to update it?

Nov 17 '05 #3
Daniel <so*******************@yahoo.com> wrote:
i have an array that i want all threads to be able to READ from
concurrently, however, at times i want to UPDATE the array. at which point i
want all threads that use it to block when they try to read from the array.
currently i do this by wrapping ALL READ AND WRITE access to the array in a
lock("foobar"){} this prevernts threads from reading from the array while it
is being written to however it ALSO keeps more then one thread from reading
the array at a time. how to solve this so that multiple threads can read the
array at the same time but whent he array is being updated all threads that
want to read from it block until it updates, and so that the code to update
the array blocks until no thread is reading from the array before it starts
to update it?


Please see ReaderWriterLock, as I posted in answer to your identical
question on another group.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 17 '05 #4
Daniel <so*******************@yahoo.com> wrote:
i have an array that i want all threads to be able to READ from
concurrently, however, at times i want to UPDATE the array. at which point i
want all threads that use it to block when they try to read from the array.
currently i do this by wrapping ALL READ AND WRITE access to the array in a
lock("foobar"){} this prevernts threads from reading from the array while it
is being written to however it ALSO keeps more then one thread from reading
the array at a time. how to solve this so that multiple threads can read the
array at the same time but whent he array is being updated all threads that
want to read from it block until it updates, and so that the code to update
the array blocks until no thread is reading from the array before it starts
to update it?


Please see ReaderWriterLock, as I posted in answer to your identical
question on another group.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 17 '05 #5
Michael McCarthy <ju*@diffjuz.com> wrote:
Use a Mutex object,


Eek no. Mutex is (in this case) equivalent to using Monitor.Enter/Exit
(aka the lock operator in C#) i.e. exclusive locking - except it's
slower than using Monitor.Enter/Exit.

That's not suitable here for exactly the reasons given in the original
post - shared access is required for reading. ReaderWriterLock is
exactly what's wanted here.

I would strongly discourage the use of Mutex unless a cross-process
synchronization mechanism is required, or unless you need the
WaitAny/WaitAll functionality.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 17 '05 #6
Michael McCarthy <ju*@diffjuz.com> wrote:
Use a Mutex object,


Eek no. Mutex is (in this case) equivalent to using Monitor.Enter/Exit
(aka the lock operator in C#) i.e. exclusive locking - except it's
slower than using Monitor.Enter/Exit.

That's not suitable here for exactly the reasons given in the original
post - shared access is required for reading. ReaderWriterLock is
exactly what's wanted here.

I would strongly discourage the use of Mutex unless a cross-process
synchronization mechanism is required, or unless you need the
WaitAny/WaitAll functionality.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 17 '05 #7

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

5
by: Bill Davidson | last post by:
Hello All: I've got a question about synchronization requiremements in a C# worker thread procedure that, among other things, sinks events from outside sources. I realize the worker thread will...
1
by: Bill Davidson | last post by:
(RESEND: I added a little more code to the sample for clarity) Hello All: I've got a question about synchronization requiremements in a C# worker thread procedure that, among other things,...
4
by: scott | last post by:
hi all, Thx to any one that can offer me help, it will be much appreciated. iv got a multithreaded program and need to use thread synchronization. The synchronization does not have to...
20
by: Bob Day | last post by:
Using VS 2003, VB, MSDE... There are two threads, A & B, that continously run and are started by Sub Main. They instantiationsl of identical code. Thread A handles call activity on telephone...
6
by: Robert Speck | last post by:
Hi there, Can anyone shed anymore light on why "Thread.Suspend()" has been deprecated by MSFT beyond what MSDN says about it. I'm not sure if I quite appreciate the various pitfalls they discuss...
13
by: arun.darra | last post by:
Are the following thread safe: 1. Assuming Object is any simple object Object* fn() { Object *p = new Object(); return p; } 2. is return by value thread safe?
9
by: RvGrah | last post by:
I'm completely new to using background threading, though I have downloaded and run through several samples and understood how they worked. My question is: I have an app whose primary form...
0
by: sundman.anders | last post by:
Hi all! I have a question about thread synchronization and c++ streams (iostreams, stringstreams, etc). When optimizing a program for a multicore processor I found that stringstream was causing...
19
by: Hapa | last post by:
Does only reading (never writing) of a variable need thread synchronisation? Thanks for help? PS. Anybody knows a Visual C++ news group?
8
by: Brad Walton | last post by:
Hello. First post, but been doing a bit of reading here. I am working on a project in Java, but decided to switch over to C# after seeing some of the additional features I can get from C#. One of...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
1
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.