473,725 Members | 2,193 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Thread Safe/Synchronized Queue question

I am working on a generic way to launch multiple similar processes (threads)
at once, but limit the number of threads running at any one time to a number
I set. As I understand it the following line makes a Queue "thread safe", so
I do not need to explicitly lock and unlock it when multiple threads are
working with it.

'Thread safe queue
Private IndexQueue As Queue = Queue.Synchroni zed(New Queue)
The following code seems to demonstrate this point quite well. However,
there is one oddity I do not understand. I have to introduce a delay
(Thread.Current Thread.Sleep(5) ) after launching each thread or else I get an
error that the queue is empty when I try to dequeue the next item. This 5 ms
delay is no big deal in this example, however I have found that if I am
doing actual work I have had to increase this value to 300, 500 or even 1000
to avoid the error.

Can anyone tell me what is going on?
Dave Coate
Option Strict On

Imports System.Threadin g

Public Class Form1
Inherits System.Windows. Forms.Form

#Region " Windows Form Designer generated code "

Public Sub New()
MyBase.New()

'This call is required by the Windows Form Designer.
InitializeCompo nent()

'Add any initialization after the InitializeCompo nent() call

End Sub

'Form overrides dispose to clean up the component list.
Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean)
If disposing Then
If Not (components Is Nothing) Then
components.Disp ose()
End If
End If
MyBase.Dispose( disposing)
End Sub

'Required by the Windows Form Designer
Private components As System.Componen tModel.IContain er

'NOTE: The following procedure is required by the Windows Form Designer
'It can be modified using the Windows Form Designer.
'Do not modify it using the code editor.
Friend WithEvents lblThreadCount As System.Windows. Forms.Label
Friend WithEvents lblTotal As System.Windows. Forms.Label
Friend WithEvents Label2 As System.Windows. Forms.Label
Friend WithEvents lblFinished As System.Windows. Forms.Label
Friend WithEvents btnGo As System.Windows. Forms.Button
Friend WithEvents dgMailboxes As System.Windows. Forms.DataGrid
<System.Diagnos tics.DebuggerSt epThrough()> Private Sub
InitializeCompo nent()
Me.lblThreadCou nt = New System.Windows. Forms.Label
Me.lblTotal = New System.Windows. Forms.Label
Me.Label2 = New System.Windows. Forms.Label
Me.lblFinished = New System.Windows. Forms.Label
Me.btnGo = New System.Windows. Forms.Button
Me.dgMailboxes = New System.Windows. Forms.DataGrid
CType(Me.dgMail boxes,
System.Componen tModel.ISupport Initialize).Beg inInit()
Me.SuspendLayou t()
'
'lblThreadCount
'
Me.lblThreadCou nt.Anchor =
CType((System.W indows.Forms.An chorStyles.Bott om Or
System.Windows. Forms.AnchorSty les.Left), System.Windows. Forms.AnchorSty les)
Me.lblThreadCou nt.Location = New System.Drawing. Point(8, 347)
Me.lblThreadCou nt.Name = "lblThreadCount "
Me.lblThreadCou nt.TabIndex = 11
Me.lblThreadCou nt.Text = "0"
'
'lblTotal
'
Me.lblTotal.Anc hor = CType((System.W indows.Forms.An chorStyles.Bott om
Or System.Windows. Forms.AnchorSty les.Right),
System.Windows. Forms.AnchorSty les)
Me.lblTotal.Loc ation = New System.Drawing. Point(280, 347)
Me.lblTotal.Nam e = "lblTotal"
Me.lblTotal.Siz e = New System.Drawing. Size(48, 23)
Me.lblTotal.Tab Index = 10
Me.lblTotal.Tex t = "0"
'
'Label2
'
Me.Label2.Ancho r = CType((System.W indows.Forms.An chorStyles.Bott om
Or System.Windows. Forms.AnchorSty les.Right),
System.Windows. Forms.AnchorSty les)
Me.Label2.Locat ion = New System.Drawing. Point(240, 347)
Me.Label2.Name = "Label2"
Me.Label2.Size = New System.Drawing. Size(24, 23)
Me.Label2.TabIn dex = 9
Me.Label2.Text = "Of"
'
'lblFinished
'
Me.lblFinished. Anchor =
CType((System.W indows.Forms.An chorStyles.Bott om Or
System.Windows. Forms.AnchorSty les.Right), System.Windows. Forms.AnchorSty les)
Me.lblFinished. Location = New System.Drawing. Point(192, 347)
Me.lblFinished. Name = "lblFinishe d"
Me.lblFinished. Size = New System.Drawing. Size(32, 23)
Me.lblFinished. TabIndex = 8
Me.lblFinished. Text = "0"
'
'btnGo
'
Me.btnGo.Anchor = CType((System.W indows.Forms.An chorStyles.Bott om Or
System.Windows. Forms.AnchorSty les.Right), System.Windows. Forms.AnchorSty les)
Me.btnGo.Locati on = New System.Drawing. Point(336, 347)
Me.btnGo.Name = "btnGo"
Me.btnGo.TabInd ex = 7
Me.btnGo.Text = "Go"
'
'dgMailboxes
'
Me.dgMailboxes. Anchor =
CType((((System .Windows.Forms. AnchorStyles.To p Or
System.Windows. Forms.AnchorSty les.Bottom) _
Or System.Windows. Forms.AnchorSty les.Left) _
Or System.Windows. Forms.AnchorSty les.Right),
System.Windows. Forms.AnchorSty les)
Me.dgMailboxes. DataMember = ""
Me.dgMailboxes. HeaderForeColor =
System.Drawing. SystemColors.Co ntrolText
Me.dgMailboxes. Location = New System.Drawing. Point(0, 3)
Me.dgMailboxes. Name = "dgMailboxe s"
Me.dgMailboxes. Size = New System.Drawing. Size(416, 328)
Me.dgMailboxes. TabIndex = 6
'
'Form1
'
Me.AutoScaleBas eSize = New System.Drawing. Size(5, 13)
Me.ClientSize = New System.Drawing. Size(416, 373)
Me.Controls.Add (Me.lblThreadCo unt)
Me.Controls.Add (Me.lblTotal)
Me.Controls.Add (Me.Label2)
Me.Controls.Add (Me.lblFinished )
Me.Controls.Add (Me.btnGo)
Me.Controls.Add (Me.dgMailboxes )
Me.Name = "Form1"
Me.Text = "Form1"
CType(Me.dgMail boxes,
System.Componen tModel.ISupport Initialize).End Init()
Me.ResumeLayout (False)

End Sub

#End Region

Private m_dt As DataTable
Private LastIndex As Integer
Private IndexQueue As Queue = Queue.Synchroni zed(New Queue)
Private m_CurrentRowInd ex As Integer
Private ThreadCount As Integer
Private FinishedCount As Integer

Private Sub Form1_Load(ByVa l sender As System.Object, ByVal e As
System.EventArg s) Handles MyBase.Load
'Create and show a datatable of items to be processed and track
progress
m_dt = New DataTable
m_dt.Columns.Ad d("Index")
m_dt.Columns.Ad d("Delay")
m_dt.Columns.Ad d("ThreadState" )
m_dt.Columns.Ad d("Result")

For ix As Integer = 0 To 10
Dim NewRow As DataRow = m_dt.NewRow
With NewRow
.Item("Index") = ix
.Item("Delay") = CInt(Rnd(ix) * 10000)
End With
m_dt.Rows.Add(N ewRow)
Next

dgMailboxes.Dat aSource = m_dt
End Sub

Private Sub btnGo_Click(ByV al sender As System.Object, ByVal e As
System.EventArg s) Handles btnGo.Click
LastIndex = m_dt.Rows.Count - 1
lblTotal.Text = CStr(LastIndex + 1)

'Fill a queue of items (index to table) to process
For m_CurrentRowInd ex = 0 To LastIndex
IndexQueue.Enqu eue(m_CurrentRo wIndex)
Next

'Process items in the queue
While IndexQueue.Coun t > 0
lblThreadCount. Text = CStr(ThreadCoun t)
lblThreadCount. Refresh()

'Launch a new thread if there are less than 20 threads running
If ThreadCount < 20 Then
Dim t As New Thread(AddressO f RunDummyTask)
t.IsBackground = False
t.Start()
End If

'Refresh Gui objects
dgMailboxes.Ref resh()
lblTotal.Refres h()
lblThreadCount. Refresh()
'needed while threads are starting
lblFinished.Tex t = CStr(FinishedCo unt)
lblFinished.Ref resh()

'Program crashes without this line. Why?
'Error: Queue Empty
Thread.CurrentT hread.Sleep(5)

End While
End Sub

Private Sub RunDummyTask()
'Increment thread count
ThreadCount += 1

'Dequeue the next index
Dim Index As Integer = CInt(IndexQueue .Dequeue)

'Get data about the process to run
Dim Delay As Integer = CInt(m_dt.Rows( Index)("Delay") )

'Show progress of the thread in the GUI
m_dt.Rows(Index )("ThreadState" ) = "Started"

'Run Process
Thread.CurrentT hread.Sleep(Del ay)

'Show progress of the thread in the GUI
m_dt.Rows(Index )("Result") = "Completed"

'Decrement the thread count
ThreadCount -= 1

'track progress in GUI
FinishedCount += 1
'needed after all threads have started
lblFinished.Tex t = CStr(FinishedCo unt)

'If this is the last thread...
If FinishedCount = LastIndex + 1 Then
Done()
End If

End Sub

Private Sub Done()
MsgBox("Done")
End Sub

End Class

Nov 21 '05 #1
0 1620

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

Similar topics

7
7870
by: sayoyo | last post by:
Hi, Is there some way that we can reuse a thread by replacing the runnable object of the thread? like a thread is not "alive" anymore, then we remove the runnable object(is it possible????) and then run it again. Thanks you very much Sayoyo
0
1177
by: Chris Stransky | last post by:
What is the easiest way to create a thread safe ListView Control ... e.g. use you own wrapper ... use a thread safe queue ... etc. There is no Synchronized or SyncRoot method available to get a synchronized version of this control. General question ... what is the reason behind making almost all of the .NET Framework controls non-thread safe by default?
1
8740
by: Frank Rizzo | last post by:
Some of the classes in the framework are marked as thread-safe in the documentation. In particular the docs say the following: "Any public static (*Shared* in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe." What exactly does this mean? Does this mean that if I call a shared method from 2 different threads, nothing whacky will happen? Also when it says that instance members...
5
15582
by: Cyrus | last post by:
I have a question regarding synchronization across multiple threads for a Hashtable. Currently I have a Threadpool that is creating worker threads based on requests to read/write to a hashtable. One function of the Hashtable is to iterate through its keys, which apparently is inherently not thread-safe. Other functions of the Hashtable include adding/modifying/deleting. To solve the synchronization issues I am doing two things: 1. Lock...
2
1376
by: Shane Story | last post by:
The Collections.Queue class has a Synchronized property. My colleague was saying that this means that we can use the queue in a multi-threaded app and not worry about normal threading issues. Is this true, or is it a faulty assumption and would he still need to use Reader/Writer locks? Thanks,
6
3139
by: fniles | last post by:
I am using VB.NET 2003 and a socket control to receive and sending data to clients. As I receive data in 1 thread, I put it into an arraylist, and then I remove the data from arraylist and send it to the client. Before adding data to the arraylist, I check if the depth of the arraylist is longer than iMaxQueueDepth, and if it is, I clear the arraylist. Is it possible that while I am clearing the arraylist, the ThreadMain at the same time...
9
1862
by: cgwalters | last post by:
Hi, I've recently been working on an application which does quite a bit of searching through large data structures and string matching, and I was thinking that it would help to put some of this CPU-intensive work in another thread, but of course this won't work because of Python's GIL. There's a lot of past discussion on this, and I want to bring it up again because with the work on Python 3000, I think it is worth trying
7
7259
by: Boki | last post by:
Multi-thread read/write to a single file. I have two processing threads, thread A and thread B; and I called my queue as Q. Thread A will feed data into Q by user input, the timing is random. Thread B will read data from Q to process; this processing will communicate with a website. I think the best Q architecture is ring buffer as large as possible.
29
9125
by: NvrBst | last post by:
I've read a bit online seeing that two writes are not safe, which I understand, but would 1 thread push()'ing and 1 thread pop()'ing be thread-safe? Basically my situation is the follows: --Thread 1-- 1. Reads TCPIP Buffer 2. Adds Buffer to Queue (q.size() to check queue isn't full, and q.push_back(...)) 3. Signals Reading Thread Event & Goes Back to Wait for More Messages on TCPIP
0
8888
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
9257
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
9176
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9113
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...
0
8097
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 launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6702
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
6011
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
4519
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...
0
4784
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?

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.