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

Home Posts Topics Members FAQ

2 different threads checking on same variable scenario

I am trying to get this straight in my head so I can implement.

I wrote a small utility some time ago in c# that utilized a handful of
threads. That scenario was one main thread manually spawning a handfull of
worker threads, then waiting for all of them to complete before moving on. I
believe I used array of ManualResetEven ts and the WaitAll() method to do
this. All the worker threads used a shared object (a common place to
collect and output data). I recall having to use 'lock' (essentially the
monitor class) to synchronize access to this object. All works great. That
was a while ago and now I have a new scenario (much simpler, I think) but I
can't get a solution straight in my head. I'm using this past example
because it is my only point of reference for mutlithreaded scenarios.

now, I'm writting a small utility (console app) that is using the asynch
programming pattern. I simply want the main thread to show some kind of
progress indicator (writing dots to screen, whatever) after calling an
asynch method and then move on after asnych operation completes. So
currently the code is structured so that the asynch operation is started and
the main thread just waits using WaitOne() until the asynch operation
signals the manualResentEve nt. Now I want to implement the progress
indicator but I'm not sure how. I'm assuming I need to get rid of the
manualResetEven t and waitOne() setup and move to checking some variable that
both threads have access to?

while (sharedVar) {do progress indicator thing}

Based on what I learned from the older project I described, I immediately
thought to just use lock. But then I thought that the lock would never be
released from the progress indicator loop in order for the other thread to
gain the lock and modify the sharedVar so the loop could end?

any input on how I should be handling this scenario would be greatly
appreciated.
May 9 '07 #1
10 4723
"David" <no****@nospam. comwrote in message
news:%2******** ********@TK2MSF TNGP02.phx.gbl. ..
while (sharedVar) {do progress indicator thing}
If the sharedVar is a boolean, you don't need any kind of lock. Assigning
a value to a bolean variable and testing the value of a boolean variable are
thread-safe operations.

May 9 '07 #2
On May 9, 3:31 pm, "Alberto Poblacion" <earthling-
quitaestoparaco ntes...@poblaci on.orgwrote:
while (sharedVar) {do progress indicator thing}

If the sharedVar is a boolean, you don't need any kind of lock. Assigning
a value to a bolean variable and testing the value of a boolean variable are
thread-safe operations.
Not true, unless sharedVar is declared to be volatile. If it's not
volatile, there's nothing to stop the reading thread from caching the
value and never rereading it from main memory.

I'd either make it volatile, or make it a property which took out a
lock for reading and writing.

Jon

May 9 '07 #3
thanks Alberto,
thats reminds me of some of the info I got during the last project... is
this because reading/writing boolean value is an 'atomic' operation?
Wondering if I'm remembering correctly. I think the same place that I
learned of atomic operations also talked about using 'volatile' keyword when
declaring the variables to be used like this? Do I need to declare my bool
shardVar in any special way?

Thanks again, I appreciate it. I looked into this stuff some time ago but
havn't used it since... I'm just putting together a really small utility
that I need to do fast so I was really hoping to not have to go through all
the research I did last time. You are saving me a lot of time. Thank you.

"Alberto Poblacion" <ea************ *************** ***@poblacion.o rgwrote
in message news:Of******** ******@TK2MSFTN GP06.phx.gbl...
"David" <no****@nospam. comwrote in message
news:%2******** ********@TK2MSF TNGP02.phx.gbl. ..
>while (sharedVar) {do progress indicator thing}

If the sharedVar is a boolean, you don't need any kind of lock.
Assigning a value to a bolean variable and testing the value of a boolean
variable are thread-safe operations.

May 9 '07 #4
On May 9, 3:48 pm, "David" <nos...@nospam. comwrote:
thats reminds me of some of the info I got during the last project... is
this because reading/writing boolean value is an 'atomic' operation?
Yes, it's atomic, but it's not volatile unless you declare it to be.
Wondering if I'm remembering correctly. I think the same place that I
learned of atomic operations also talked about using 'volatile' keyword when
declaring the variables to be used like this? Do I need to declare my bool
shardVar in any special way?
See http://pobox.com/~skeet/csharp/threads/volatility.shtml

Jon

May 9 '07 #5
whoa, quick responses on this thread. Thanks!
I replied before seeing Jon's reply. Jon answered my question about
declaring it 'specially'. Use volatile.

thanks Jon.

"Jon Skeet [C# MVP]" <sk***@pobox.co mwrote in message
news:11******** **************@ y5g2000hsa.goog legroups.com...
On May 9, 3:31 pm, "Alberto Poblacion" <earthling-
quitaestoparaco ntes...@poblaci on.orgwrote:
while (sharedVar) {do progress indicator thing}

If the sharedVar is a boolean, you don't need any kind of lock.
Assigning
a value to a bolean variable and testing the value of a boolean variable
are
thread-safe operations.

Not true, unless sharedVar is declared to be volatile. If it's not
volatile, there's nothing to stop the reading thread from caching the
value and never rereading it from main memory.

I'd either make it volatile, or make it a property which took out a
lock for reading and writing.

Jon

May 9 '07 #6
thanks Jon. I remember now, I have your page on my browser favorites... it
helped me before. I'll revew it again.

"Jon Skeet [C# MVP]" <sk***@pobox.co mwrote in message
news:11******** **************@ e51g2000hsg.goo glegroups.com.. .
On May 9, 3:48 pm, "David" <nos...@nospam. comwrote:
>thats reminds me of some of the info I got during the last project... is
this because reading/writing boolean value is an 'atomic' operation?

Yes, it's atomic, but it's not volatile unless you declare it to be.
>Wondering if I'm remembering correctly. I think the same place that I
learned of atomic operations also talked about using 'volatile' keyword
when
declaring the variables to be used like this? Do I need to declare my
bool
shardVar in any special way?

See http://pobox.com/~skeet/csharp/threads/volatility.shtml

Jon

May 9 '07 #7
"David" <no****@nospam. comwrote in message
news:%2******** ********@TK2MSF TNGP02.phx.gbl. ..
>I am trying to get this straight in my head so I can implement.

I wrote a small utility some time ago in c# that utilized a handful of
threads. That scenario was one main thread manually spawning a handfull of
worker threads, then waiting for all of them to complete before moving on.
I believe I used array of ManualResetEven ts and the WaitAll() method to do
this. All the worker threads used a shared object (a common place to
collect and output data). I recall having to use 'lock' (essentially the
monitor class) to synchronize access to this object. All works great. That
was a while ago and now I have a new scenario (much simpler, I think) but
I can't get a solution straight in my head. I'm using this past example
because it is my only point of reference for mutlithreaded scenarios.

now, I'm writting a small utility (console app) that is using the asynch
programming pattern. I simply want the main thread to show some kind of
progress indicator (writing dots to screen, whatever) after calling an
asynch method and then move on after asnych operation completes. So
currently the code is structured so that the asynch operation is started
and the main thread just waits using WaitOne() until the asynch operation
signals the manualResentEve nt. Now I want to implement the progress
indicator but I'm not sure how. I'm assuming I need to get rid of the
manualResetEven t and waitOne() setup and move to checking some variable
that both threads have access to?

while (sharedVar) {do progress indicator thing}

Based on what I learned from the older project I described, I immediately
thought to just use lock. But then I thought that the lock would never be
released from the progress indicator loop in order for the other thread to
gain the lock and modify the sharedVar so the loop could end?

any input on how I should be handling this scenario would be greatly
appreciated.

No need for a shared variable, just keep synchronizing both threads as you
did, but use the WaitOne overhead that takes a TimeSpan. Set the Timespan to
a reasonable value depending on the duration of the other threads task,
update the user interface (the progress indicator) each time WaitOne
times-out.

Willy.
May 9 '07 #8
interesting... I'll check out that overload. Do you see this as just
'another' way to accomplish this or are there certain pros/cons that may
make one a better choice than the other (shared var vs waitOne overload with
timespan)? Without looking yet the waitOne with timespan overload sounds
like it may be more fitting for my particular need (progress indicator)... I
was probably going to just use the shared var to control the loop and use
console.writeli ne()'s and short thread.sleep()' s within the loop.

"Willy Denoyette [MVP]" <wi************ *@telenet.bewro te in message
news:AE******** *************** ***********@mic rosoft.com...
"David" <no****@nospam. comwrote in message
news:%2******** ********@TK2MSF TNGP02.phx.gbl. ..
>>I am trying to get this straight in my head so I can implement.

I wrote a small utility some time ago in c# that utilized a handful of
threads. That scenario was one main thread manually spawning a handfull
of worker threads, then waiting for all of them to complete before moving
on. I believe I used array of ManualResetEven ts and the WaitAll() method
to do this. All the worker threads used a shared object (a common place
to collect and output data). I recall having to use 'lock' (essentially
the monitor class) to synchronize access to this object. All works great.
That was a while ago and now I have a new scenario (much simpler, I
think) but I can't get a solution straight in my head. I'm using this
past example because it is my only point of reference for mutlithreaded
scenarios.

now, I'm writting a small utility (console app) that is using the asynch
programming pattern. I simply want the main thread to show some kind of
progress indicator (writing dots to screen, whatever) after calling an
asynch method and then move on after asnych operation completes. So
currently the code is structured so that the asynch operation is started
and the main thread just waits using WaitOne() until the asynch operation
signals the manualResentEve nt. Now I want to implement the progress
indicator but I'm not sure how. I'm assuming I need to get rid of the
manualResetEve nt and waitOne() setup and move to checking some variable
that both threads have access to?

while (sharedVar) {do progress indicator thing}

Based on what I learned from the older project I described, I immediately
thought to just use lock. But then I thought that the lock would never be
released from the progress indicator loop in order for the other thread
to gain the lock and modify the sharedVar so the loop could end?

any input on how I should be handling this scenario would be greatly
appreciated.


No need for a shared variable, just keep synchronizing both threads as you
did, but use the WaitOne overhead that takes a TimeSpan. Set the Timespan
to a reasonable value depending on the duration of the other threads task,
update the user interface (the progress indicator) each time WaitOne
times-out.

Willy.


May 9 '07 #9
On Wed, 09 May 2007 08:58:29 -0700, David <no****@nospam. comwrote:
interesting... I'll check out that overload. Do you see this as just
'another' way to accomplish this or are there certain pros/cons that may
make one a better choice than the other
To me, it depends on what you intend to do in your main thread's loop.

Because you are implementing a console application here, it seems to me
that a third way to implement this would be to simply have the main thread
call some "do work" function repeatedly. That function would make as much
progress toward the goal as you want for each "update" (where an "update"
may just be writing a new "." to the console output), would return to the
caller so it can handle the "update" and when called again would resume
where it left off.

This would be especially appropriate if the work you need to do is already
conveniently broken into multiple chunks (for example, it involves a loop
that processes a list of files), where the the top-level loop in your main
thread can handle managing the list of chunks to process (that way the "do
work" function doesn't even need to maintain any state between calls...the
caller is handling that for it).

Depending on just what you intended to do in your "do progress indicator
thing" loop, there may be a fourth option. That is, use an auto-reset
wait event to block the main thread between progress updates, a flag to
indicate when the work has been done, and then have the worker thread set
the flag when it's done, and intermittently set the wait event to indicate
to the main thread to update the progress.

To summarize, here's four different ways I see as having been mentioned in
this thread:

#1:
volatile bool fDone = false;

// start worker thread

while (!fDone)
{
Sleep(...);
// update progress
}

In the worker thread, fDone is set when the work has been completed.

#2:
AutoResetEvent event = new AutoResetEvent( false);

// start worker thread

while (!event.WaitOne (new TimeSpan(0, 0, 1), false))
{
// update progress
}

In the worker thread, the event is set when the work has been completed.

#3:
AutoResetEvent event = new AutoResetEvent( false);
volatile bool fDone = false;

// start worker thread

while (!fDone)
{
event.WaitOne() ;
// update progress
}

In the worker thread, the event is set when the main thread should update
the progress indication, and the fDone flag is set when the work is done..

#4:
foreach (WorkItem item in WorkCollection)
{
item.DoWork();
// update progress
}

There's no worker thread. The main thread just iteratively performs work,
updating progress between calls to the method that does work. You may or
may not have exactly the above data structure design. For example,
instead of having a class that encapsulates the work items, you might just
have some list of objects (strings containing filenames, for example), and
a method in some other class (your main Program class, for example) that
does some work on a single object (takes a filename and does some
processing on that file, for example).

To compare and contrast the various methods:

The first two provide progress updates on a strictly time-based
interval. The upside is that you always have some feedback to the user.
The downside is that feedback doesn't really indicate what progress has
been made; in fact, the worker thread could completely lock up and you'd
still show progress as being made.

Between the first two, I don't see too much difference. They both use
slightly different mechanisms to accomplish very much the same thing.

The second two provide progress updates that are tied to the actual
work being done. The upside is that you have direct indication of the
progress being made. The downside is that the feedback may or may not be
provided in a timely manner. Both of the second pair do rely on the work
being done having regular "checkpoint s" at which it makes sense to update
the progress.

Between the second pair, probably the biggest difference is that with
option #4, you don't even have to make a new thread. It does rely on the
main thread having more involvement with the work being done, however. If
you want greater encapsulation, option #3 is probably more desirable.

This is not even a complete analysis. As you can see, there's a wide
variety of approaches to doing what you want. They are roughly equivalent
in that they all get the job done, but they all have different specific
behaviors, and different demands on the architecture of the part of your
code that actually does work.

I hope I have helped, rather than further confusing the issue. I realize
sometimes all someone wants is to be told "do it this way"...I even find
myself in that position sometimes. :)

Pete
May 9 '07 #10

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

Similar topics

10
3053
by: MikeE | last post by:
Hi all, What's the best way to queue up and wait for number of threads to complete. This problem was trivial in VC++ 6 but I'm finding it rather hard to solve in VB.NET. My calculations run about 2 mins each (on a 2.8 Ghz Xeon and the server range from 2 to 8 processors) (give or take about 15 secs). I have 8 sets of calculations to do (in another app I have 121) all the same calc just different data. But the rest of the processing...
5
2064
by: Rich | last post by:
Hi there, For a quite big application, I need to get large amount of data within a static library (xxx.lib) and put them in a database (a class, say we call it CData), and then make it accessible by a few different dynamic library files (yyy.dll, …). I’ve tried to create a global class object of CData*, say pData, by declaring it as an external in the header and initiate it in the cpp of a dll file. But it doesn’t work. Other dlls...
4
1418
by: izhar.wallach | last post by:
Hi all, I've noticed an odd behavior of the linker while trying to compile the code below. The linking did not fail even though variable a1 (A2.cpp) was defined as extern in namespace A2 while its actual deceleration was in namespace A1 (main.cpp). Thus, the assignment a1 = &a2 (A2.cpp) should have failed. I used the following for compilation: g++ -Wall -pedantic -ansi main.cpp A2.cpp gcc version:
4
1958
by: sunilkher | last post by:
Here is a small sample program that I have. #include <stdlib.h> #include <pthread.h> #include <string> using namespace std; pthread_t threads; pthread_attr_t thr_attr;
15
2605
by: Bryce K. Nielsen | last post by:
I have an object that starts a thread to do a "process". One of the steps inside this thread launches 12 other threads via a Delegate.BeginInvoke to process. After these 12 threads are launched, the main thread waits. At the completion of each subthread, the mainthread checks all 12 thread objects to see if they are done. If they are, raise an event that says we're done. So, it's kinda like this: ProcessThread - Creates a ProcessObject
5
4760
by: zxo102 | last post by:
Hi, I am doing a small project using socket server and thread in python. This is first time for me to use socket and thread things. Here is my case. I have 20 socket clients. Each client send a set of sensor data per second to a socket server. The socket server will do two things: 1. write data into a file via bsddb; 2. forward the data to a GUI written in wxpython. I am thinking the code should work as follow (not sure it is feasible)...
8
4395
by: JackC | last post by:
Hi, I am trying to get posix threads working from within an object, heres some code: int NConnection::TheadControl() { int thread_id; pthread_t new_connection; pthread_create(&new_connection, NULL, PriC, (void *)thread_id);
167
8277
by: darren | last post by:
Hi I have to write a multi-threaded program. I decided to take an OO approach to it. I had the idea to wrap up all of the thread functions in a mix-in class called Threadable. Then when an object should run in its own thread, it should implement this mix-in class. Does this sound like plausible design decision? I'm surprised that C++ doesn't have such functionality, say in its STL. This absence of a thread/object relationship in...
5
2758
by: rahullko05 | last post by:
Hi, I am developing forum website as my final year project. I am having problem in generating different URLs but keeping the same page.. Scenario: I am showing threads for different languages in different page, but since format of data is same for threads of all the languages, so what i planned was, to write one single xhtml page, which will be populated by data at run time using php/mysql. but i want to show different URLs for different...
0
8420
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
8324
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
8740
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...
0
8617
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
6176
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
5642
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4330
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2743
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
1733
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.