473,657 Members | 2,566 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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 2288
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.Threadin g;

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.WriteLi ne("Mutex Sample ...");
// Create Mutex initialOwned, with name of "MyMutex".
gM1 = new Mutex(true,"MyM utex");
// Create Mutex initialOwned, with no name.
gM2 = new Mutex(true);
Console.WriteLi ne(" - 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(M utex[] of gM1 and gM2)
t2.Start( ); // Does Mutex.WaitOne(M utex gM1)
t3.Start( ); // Does Mutex.WaitAny(M utex[] of gM1 and gM2)
t4.Start( ); // Does Mutex.WaitOne(M utex gM2)

Thread.Sleep(20 00);
Console.WriteLi ne(" - Main releases gM1");
gM1.ReleaseMute x( ); // t2 and t3 will end and signal

Thread.Sleep(10 00);
Console.WriteLi ne(" - Main releases gM2");
gM2.ReleaseMute x( ); // t1 and t4 will end and signal

// Waiting until all four threads signal that they are done.
WaitHandle.Wait All(evs);
Console.WriteLi ne("... Mutex Sample");
}

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

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

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

public void t4Start( )
{
Console.WriteLi ne("t4Start started, gM2.WaitOne( )");
gM2.WaitOne( ); // Waits until Mutex gM2 is released
Console.WriteLi ne("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(M utex[])
t2Start started, gM1.WaitOne( )
t3Start started, Mutex.WaitAny(M utex[])
t4Start started, gM2.WaitOne( )
- Main releases gM1
t2Start finished, gM1.WaitOne( ) satisfied
t3Start finished, Mutex.WaitAny(M utex[])
- Main releases gM2
t1Start finished, Mutex.WaitAll(M utex[]) 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.Threadin g;

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.WriteLi ne("Mutex Sample ...");
// Create Mutex initialOwned, with name of "MyMutex".
gM1 = new Mutex(true,"MyM utex");
// Create Mutex initialOwned, with no name.
gM2 = new Mutex(true);
Console.WriteLi ne(" - 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(M utex[] of gM1 and gM2)
t2.Start( ); // Does Mutex.WaitOne(M utex gM1)
t3.Start( ); // Does Mutex.WaitAny(M utex[] of gM1 and gM2)
t4.Start( ); // Does Mutex.WaitOne(M utex gM2)

Thread.Sleep(20 00);
Console.WriteLi ne(" - Main releases gM1");
gM1.ReleaseMute x( ); // t2 and t3 will end and signal

Thread.Sleep(10 00);
Console.WriteLi ne(" - Main releases gM2");
gM2.ReleaseMute x( ); // t1 and t4 will end and signal

// Waiting until all four threads signal that they are done.
WaitHandle.Wait All(evs);
Console.WriteLi ne("... Mutex Sample");
}

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

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

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

public void t4Start( )
{
Console.WriteLi ne("t4Start started, gM2.WaitOne( )");
gM2.WaitOne( ); // Waits until Mutex gM2 is released
Console.WriteLi ne("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(M utex[])
t2Start started, gM1.WaitOne( )
t3Start started, Mutex.WaitAny(M utex[])
t4Start started, gM2.WaitOne( )
- Main releases gM1
t2Start finished, gM1.WaitOne( ) satisfied
t3Start finished, Mutex.WaitAny(M utex[])
- Main releases gM2
t1Start finished, Mutex.WaitAll(M utex[]) 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.c om> 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 ReaderWriterLoc k, as I posted in answer to your identical
question on another group.

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 17 '05 #4
Daniel <so************ *******@yahoo.c om> 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 ReaderWriterLoc k, as I posted in answer to your identical
question on another group.

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 17 '05 #5
Michael McCarthy <ju*@diffjuz.co m> 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. ReaderWriterLoc k 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.co m>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 17 '05 #6
Michael McCarthy <ju*@diffjuz.co m> 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. ReaderWriterLoc k 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.co m>
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
2596
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 be interrupted to handle an incoming event (and the flow of execution subsequently diverted to the respective event handler). My question is at what point or points could this interruption occur. Will it only occur when the worker thread is...
1
1781
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, sinks events from outside sources. I realize the worker thread will be interrupted to handle an incoming event (and the flow of execution subsequently diverted to the respective event handler). My question is at what point or points could this...
4
3192
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 work across multiple processes just the one. I was wondering if any one new which one used the least overhead. Im at current using mutexes but was wondering if there was something a bit
20
2391
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 line 1 and Thread B handles call activity on telephone line 2. They use a common SQL datasource, but all DataSets are unique to each thread. Is there a way for thread A to occasionally communication to thread B that something has happened? ...
6
1418
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 but using it under certain circumstances still seems reasonable. For instance, I want to display a small modal dialog with a "Cancel" button which allows the user to abort a background thread. If the user clicks this button, I then want to prompt...
13
3583
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
18019
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 will almost always lead to the user opening a certain child window that's fairly resource intensive to load. Is it possible to load this form in a backgroundworker and then use the Show method and hide method as necessary? Anyone know of
0
1972
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 a LOT of synchronization overhead. After a bit of digging I concluded that this synchronization has to do with the access to a global locale inside the stream. The problem can be seen by running the small distilled benchmark code
19
2297
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
2975
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 the big changes I want to make is event-driven code (rather than the linear flow I had in Java). I have spent a week or so searching Google, talking to a couple of programming friends, and just chewing on it in my brain. I think I have an ok handle...
0
8392
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8305
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8825
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8732
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
6163
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 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 a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
4151
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
2726
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
1953
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
2
1611
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.