473,378 Members | 1,415 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,378 software developers and data experts.

Thread synchronization - part II

Hi there

My work on threads continues with more or less success. Here is what I'm
trying to do:
Class JobAgent is incharged for some tasks and when it's called it starts
thread which performs the job. Application contains one list of agents
that are idle at the moment and list of busy agents. In loop it checks if
there
are agents in idle list and if there are some, it starts them.

I'm using events from JobAgent class to notify main thread in order to
update
lists. Problem is that I'm not sure that I use locks at right places and I
have
a problem to understand what it is happening when of the threads fire event
and
code in main thread is called (agent thread is interrupting main thread and
start
execution of event handler - fogy at the moment). Am I missing
synchronization
in that context?

Thx. in advance

Best regards
Ivan

using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.Threading;
using System.Diagnostics;

namespace Threads
{
/// <summary>
/// Summary description for Form1.
/// </summary>
public class frmMain : System.Windows.Forms.Form
{
private System.Windows.Forms.Button btnStartThreads;

protected ArrayList idleAgents = new ArrayList ();
protected ArrayList busyAgents = new ArrayList ();

/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components = null;

public frmMain()
{
InitializeComponent();
}

/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if (components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}

#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.btnStartThreads = new System.Windows.Forms.Button();
this.SuspendLayout();
//
// btnStartThreads
//
this.btnStartThreads.Location = new System.Drawing.Point(48, 48);
this.btnStartThreads.Name = "btnStartThreads";
this.btnStartThreads.Size = new System.Drawing.Size(88, 23);
this.btnStartThreads.TabIndex = 0;
this.btnStartThreads.Text = "&Start threads";
this.btnStartThreads.Click += new
System.EventHandler(this.btnStartThreads_Click);
//
// frmMain
//
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.ClientSize = new System.Drawing.Size(176, 125);
this.Controls.Add(this.btnStartThreads);
this.Name = "frmMain";
this.Text = "Thread test";
this.ResumeLayout(false);

}
#endregion

/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.Run(new frmMain());
}

private void btnStartThreads_Click(object sender, System.EventArgs e)
{
// create job agents and put them in idleAgents list
for (int c = 0;c < 5;c++)
{
JobAgent agent = new JobAgent ();
agent.AgentFinished +=new
JobAgentNotificationEventHandler(agent_AgentFinish ed);
agent.AgentStarted +=new
JobAgentNotificationEventHandler(agent_AgentStarte d);
idleAgents.Add (agent);
}
// check if there are agents in idleAgents list and start them
while (true)
{
if (idleAgents.Count > 0)
((JobAgent)idleAgents[0]).Start ();
}
}

// called when agent finished
private void agent_AgentFinished(JobAgent jobAgent)
{
// move agent from busyAgents in to idleAgents
busyAgents.Remove (jobAgent);
idleAgents.Add (jobAgent);
}

// called when agent started
private void agent_AgentStarted(JobAgent jobAgent)
{
// move agent from idleAgents in to busyAgents
busyAgents.Add (jobAgent);
idleAgents.Remove (jobAgent);
}
}

public delegate void JobAgentNotificationEventHandler (JobAgent jobAgent);

public class JobAgent
{
private bool isBusy = false;
private Object busyLock = new Object ();
private static Object eventLock = new Object ();

protected Thread thread = null;
public event JobAgentNotificationEventHandler AgentStarted = null;
public event JobAgentNotificationEventHandler AgentFinished = null;

public void Start ()
{
lock (busyLock)
{
if (isBusy == true)
return;
else
isBusy = true;
}
thread = new Thread (new ThreadStart (this.Run));
thread.Start ();
// fire event that thread is starting
lock (eventLock)
{
if (AgentStarted != null)
AgentStarted (this);
}
}

public void Run ()
{
Random rnd = new Random ();

Debug.WriteLine ("Thread num. " + Convert.ToString
(Thread.CurrentThread.GetHashCode ()) + " started");
Thread.Sleep (2000 + rnd.Next (5)*1000);
Debug.WriteLine ("Thread num. " + Convert.ToString
(Thread.CurrentThread.GetHashCode ()) + " finished");
lock (busyLock)
{
isBusy = false;
}
lock (eventLock)
{
if (AgentFinished != null)
AgentFinished (this);
}
}
}
}
Nov 16 '05 #1
0 1216

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

Similar topics

20
by: Ken Godee | last post by:
module1 calls a function in module2 module2 starts a thread that calls a function in module3 and then returns to module1 thread finishes and I need the return value from the thread to use in...
1
by: Alex Hunsley | last post by:
I'm writing a test script in python for pulling web pages from a web server using urllib2 and cookielib. Since the main thing I am testing is what happens when concurrent requests are made to the...
7
by: Ivan | last post by:
Hi there My work on threads continues with more or less success. Here is what I'm trying to do: Class JobAgent is incharged for some tasks and when it's called it starts thread which performs...
20
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...
6
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...
3
by: tcomer | last post by:
Hello! I'm working on an asynchronous network application that uses multiple threads to do it's work. I have a ChatClient class that handles the basic functionality of connecting to a server and...
9
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...
16
by: Paul Schwann | last post by:
Hi group, I am relatively new to C# (although I have a lot of programming excperience in other languages like Java and C). Currently I am searching for a solution to this problem: Suppose you...
29
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: ...
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 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 former...
0
by: ryjfgjl | last post by:
In our work, we often need to import Excel data into databases (such as MySQL, SQL Server, Oracle) for data analysis and processing. Usually, we use database tools like Navicat or the Excel import...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...

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.