473,569 Members | 2,756 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Syncronizing two threads

I have got two classes: One producing data and one consuming data.
Running as two threads, the first class adds data to a job-queue, the
second one fetches data from the queue.

My problem is that the consumer thread spends most of its time waiting
for data to appear on the queue. How can I tell the consumer that data
is available, without running useless circles in an do...loop?

Thanks in advance!
Iason
Code example below:

Class Jobs
Private o As New Generic.Queue(O f Integer)
Private b As Boolean

Public Property Done() As Boolean
Get
Return o.Count = 0 And b
End Get
Set(ByVal value As Boolean)
b = value
End Set
End Property

Public Sub Add(ByVal n As Integer)
o.Enqueue(n)
End Sub

Public Function Fetch() As Integer
If o.Count 0 Then
Return o.Dequeue
Else
Return Nothing
End If
End Function

End Class

Class Producer

Public Sub Produce(ByVal o As Object)
Dim q As Jobs = CType(o, Jobs)

For i As Integer = 1 To 100
q.Add(i)
Threading.Threa d.Sleep(100)
Next

o.Done = True

End Sub

End Class

Class Consumer

Public Sub Comsume(ByVal o As Object)
Dim q As Jobs = CType(o, Jobs)

Do While Not q.Done
Debug.Print(q.F etch)
Loop

End Sub

End Class
Oct 25 '07 #1
12 1202
How can I tell the consumer that data
is available, without running useless circles in an do...loop?
Why not just raise an Event when the data is available?

Thanks,

Seth Rowe

Oct 25 '07 #2
"Iason Mavip" <op*****@cathol ic.orgschrieb
I have got two classes: One producing data and one consuming data.
Running as two threads, the first class adds data to a job-queue,
the second one fetches data from the queue.

My problem is that the consumer thread spends most of its time
waiting for data to appear on the queue. How can I tell the consumer
that data is available, without running useless circles in an
do...loop?

Thanks in advance!
Iason
Code example below:

Class Jobs
Private o As New Generic.Queue(O f Integer)
Private b As Boolean

Public Property Done() As Boolean
Get
Return o.Count = 0 And b
End Get
Set(ByVal value As Boolean)
b = value
End Set
End Property

Public Sub Add(ByVal n As Integer)
o.Enqueue(n)
End Sub

Public Function Fetch() As Integer
If o.Count 0 Then
Return o.Dequeue
Else
Return Nothing
End If
End Function

End Class

Class Producer

Public Sub Produce(ByVal o As Object)
Dim q As Jobs = CType(o, Jobs)

For i As Integer = 1 To 100
q.Add(i)
Threading.Threa d.Sleep(100)
Next

o.Done = True

End Sub

End Class

Class Consumer

Public Sub Comsume(ByVal o As Object)
Dim q As Jobs = CType(o, Jobs)

Do While Not q.Done
Debug.Print(q.F etch)
Loop

End Sub

End Class
First, it's strongly recommended to switch Option Strict On.

Untested(!) solution:

Class Jobs
Public Event ItemAdded()
Public Event DoneChanged()

Private o As New Generic.Queue(O f Integer)
Private b As Boolean

Public Property Done() As Boolean
Get
Return o.Count = 0 And b
End Get
Set(ByVal value As Boolean)
b = value
RaiseEvent DoneChanged()
End Set
End Property

Public Sub Add(ByVal n As Integer)
o.Enqueue(n)
RaiseEvent ItemAdded()
End Sub

Public Function Fetch() As Integer
If o.Count 0 Then
Return o.Dequeue
Else
Return 0
End If
End Function

End Class

Class Producer

Public Sub Produce(ByVal q As Jobs)

For i As Integer = 1 To 100
SyncLock q
q.Add(i)
End SyncLock
Threading.Threa d.Sleep(100)
Next

q.Done = True

End Sub

End Class

Class Consumer

Private ARE As New Threading.AutoR esetEvent(False )

Public Sub Comsume(ByVal q As Jobs)

AddHandler q.ItemAdded, AddressOf OnItemAdded
AddHandler q.DoneChanged, AddressOf OnDoneChanged

Do
ARE.WaitOne()

Do Until q.Done
Dim value As Integer
SyncLock q
value = q.Fetch
End SyncLock
Debug.Print(val ue.ToString)
If value = 0 Then Exit Do
Loop
Loop Until q.Done

End Sub
Private Sub OnItemAdded()
ARE.Set()
End Sub
Private Sub OnDoneChanged()
ARE.Set()
End Sub

End Class
The AutoResetEvent is the key. It waits til the queue is "done" or an item
has been added w/o CPU usage.

Are you sure that the Queue will never contain 0? Otherwise, returning
0 for an empty queue is ambiguous. I would add a Count property, or
you can Inherit from the generic Queue.

(BTW, I'd prefer stopping the Consumer processing the queue instead of
setting a Done flag in a queue, but maybe there's a reason for you doing it
this way. In addition, the Done property could be set from True to False
which wouldn't make sense.)
Armin

Oct 25 '07 #3
rowe_newsgroups schrieb:
>How can I tell the consumer that data
is available, without running useless circles in an do...loop?

Why not just raise an Event when the data is available?
Thanks for your suggestion; I already thought about using an event to
spawn a new consumer thread each time data becomes available. But to
ensure data consistency I would feel a lot better if only one thread
would access the database at a time - I'm dealing with an archaic Access
database :-/
Oct 25 '07 #4
"Armin Zingler" <az*******@free net.deschrieb
Public Sub Comsume(ByVal q As Jobs)

AddHandler q.ItemAdded, AddressOf OnItemAdded
AddHandler q.DoneChanged, AddressOf OnDoneChanged

Do
To make it bullet-proof, this must be

Do Until q.Done
ARE.WaitOne()

Do Until q.Done
Dim value As Integer
SyncLock q
value = q.Fetch
End SyncLock
Debug.Print(val ue.ToString)
If value = 0 Then Exit Do
Loop
Loop Until q.Done
Loop

Because, theoretically, the Producer might be ready and has set q.done =
true before the Consumer has attached the event handlers, so the Consumer
would wait forever. (one reason why other applications might hang or crash
only every 100st time and nobody knows why).
Armin

Oct 25 '07 #5
Iason,

Why are you using an assynchonized process, when you need a synchronised
proces?

Cor

Oct 26 '07 #6
"Cor Ligthert[MVP]" <no************ @planet.nlschri eb
Iason,

Why are you using an assynchonized process, when you need a
synchronised proces?
Why do you think this? "A synchronized process" is a contradictive term in
itself. To synchronize, you have to have at least two processes (as you
know). You probably assume that putting one item in the queue has to wait
until the previous item has been processed, but this would blocks the thread
(the Producer class). I guess this is what the OP wants to avoid.
Armin

Oct 26 '07 #7
Armin,

I am more curious why somebody would create a two processes for getting and
consuming data, while that is most often a very serialized process. (This
beside the situations where the periphery is not as downloading using
yourself slow lines while the provider is giving it to you very fast).

In my idea in a serialized process you know that there is data available to
consume while in a paralyzed process you need to do extras, while the effort
will be that the processor will be (probably not visible) slower.

However there can be a reason I don't know. The one you gave me is obvious,
however I always want to know the why. I come from a not so discipliner
culture you know.

:-)

Cor

Oct 26 '07 #8
"Cor Ligthert[MVP]" <no************ @planet.nlschri eb
I come from a not
so discipliner culture you know.

:-)
Even with your smiley, I don't know what this (quoted) nonsense should tell
me.
Armin

Oct 26 '07 #9
Iason Mavip <op*****@cathol ic.orgwrote in news:ffq2pf$av$ 1
@newsreader2.ne tcologne.de:
Thanks for your suggestion; I already thought about using an event to
spawn a new consumer thread each time data becomes available. But to
ensure data consistency I would feel a lot better if only one thread
would access the database at a time - I'm dealing with an archaic Access
database :-/
You could lock the record using status flags?
Oct 26 '07 #10

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

Similar topics

3
5382
by: Ronan Viernes | last post by:
Hi, I have created a python script (see below) to count the maximum number of threads per process (by starting new threads continuously until it breaks). ###### #testThread.py import thread, sys
0
1999
by: Al Tobey | last post by:
I was building perl 5.8.2 on RedHat Enterprise Linux 3.0 (AS) today and noticed that it included in it's ccflags "-DTHREADS_HAVE_PIDS." I am building with -Dusethreads. With newer Linux distributions using the Native Posix Threading Layer (NPTL), this isn't entirely true anymore and is AFAIK unsupported (using a pid to signal/identify...
6
3183
by: m | last post by:
Hello, I have an application that processes thousands of files each day. The filenames and various related file information is retrieved, related filenames are associate and placed in a linked list within a single object, which is then placed on a stack(This cuts down thread creation and deletions roughly by a factor of 4). I create up to...
34
10753
by: Kovan Akrei | last post by:
Hi, I would like to know how to reuse an object of a thread (if it is possible) in Csharp? I have the following program: using System; using System.Threading; using System.Collections; public class A {
7
1863
by: Mr. Mountain | last post by:
In the following code I simulate work being done on different threads by sleeping a couple methods for about 40 ms. However, some of these methods that should finish in about 40 -80 ms take as long as 2300 ms to complete. This is fairly rare, but the test code below will definitely show it. Somehow, I must not have my design right. The...
10
1662
by: [Yosi] | last post by:
I would like to know how threads behavior in .NET . When an application create 4 threads for example start all of them, the OS task manager will execute all 4 thread in deterministic order manes, OS execute (All have same priority) Thread#1 may be other threads, Thread#2 may be other threads, Thread#3 may be other threads,
3
5957
by: mjheitland | last post by:
Hi, I like to know how many threads are used by a Threading.Timer object. When I create a Threading.Timer object calling a short running method every 5 seconds I expected to have one additional ThreadPool thread. And that is exactly what MS VIsual Studio shows. But when I run Processexplorer or Taskmanager I see 2 additional threads,...
10
1744
by: Darian | last post by:
Is there a way to find all the thread names that are running in a project? For example, if I have 5 threads T1, T2, T3, T4, T5...and T2, T4, and T5 are running...I want to be able to know that T2, T4 and T5 are already running. Thanks, Darian
0
983
by: Rob Smeets | last post by:
Hi, i'm trying to grasp the concept of syncronizing threads, but without success Here is the situation: I'm using an object which connects to a server. After connection i want to send informational requests. If i send a request and the object is not connected yet i tell the Component to connect(sub RequestInfo).
0
7697
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...
0
7612
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...
0
7924
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. ...
0
8120
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...
0
7968
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...
0
6283
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
0
5219
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...
0
3653
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...
0
937
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...

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.