473,503 Members | 2,135 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(Of 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.Thread.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.Fetch)
Loop

End Sub

End Class
Oct 25 '07 #1
12 1195
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*****@catholic.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(Of 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.Thread.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.Fetch)
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(Of 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.Thread.Sleep(100)
Next

q.Done = True

End Sub

End Class

Class Consumer

Private ARE As New Threading.AutoResetEvent(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(value.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*******@freenet.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(value.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.nlschrieb
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.nlschrieb
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*****@catholic.orgwrote in news:ffq2pf$av$1
@newsreader2.netcologne.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
"Armin Zingler" <az*******@freenet.dewrote in
news:Oh**************@TK2MSFTNGP03.phx.gbl:
Even with your smiley, I don't know what this (quoted) nonsense should
tell me.
I find it hard to understand alot of Cor's comments too... Most of the time
it's jibberish to me.
Oct 26 '07 #11
On Oct 25, 4:47 am, Iason Mavip <opus...@catholic.orgwrote:
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(Of 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.Thread.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.Fetch)
Loop

End Sub

End Class
See the following article for a correct implementation of the producer-
consumer pattern. Unfortunately, the example is in C#.

http://www.yoda.arachsys.com/csharp/...eadlocks.shtml
Oct 29 '07 #12
Brian Gideon schrieb:
See the following article for a correct implementation of the producer-
consumer pattern. Unfortunately, the example is in C#.
Thanks for the link, I guess that's exactly what I was looking for.
Oh, and C# shouldn't be a problem.

Iason
Oct 30 '07 #13

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

Similar topics

3
5377
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...
0
1997
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...
6
3170
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...
34
10733
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; ...
7
1858
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...
10
1657
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,...
3
5955
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...
10
1734
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...
0
978
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...
0
7093
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...
0
7287
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,...
0
7353
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...
1
7011
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
7468
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...
0
5596
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,...
1
5023
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...
0
1521
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 ...
1
747
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.