(Any One There)
I am working on vehicle tracking system:-
I have n number of buses say
b1t1(start at 7 am and stop at 7 pm)
bt2 (start at 8 am and stop at 8 pm) and bt3 (start at 9 am and stop at 9 pm)
,where t is start time of a bus
now i have such such busses in a list.
now for each bus in a list i pickup one busobject and pass to method MyMethod(bus bt);what i want is ,I want to pass b1,b2,b3 to MyMethod(bus bt) and and of each bus say b1--start its own proccessing of MyMethod(bus bt)
and then for b2 --start its own proccessing of MyMethod(bus bt)
and then for b3----start its own proccessing of MyMethod(bus bt)
all b1 b2 b3 should start there own processing in parallel (must be thread safe---isn it approprate to use word thread safe i donn know)....
---I tried using thread but thread does not acces the method in parallel...
more explanation
i have only one method and will be passing bus object in a loop to MyMethod(bus bt) one by one ... but i want thread t1/t2...tn should access this method in parallel...because when thread for b1 is running simultinuously thread for b2 should run.
enter c public bool SchedulerEntryPointFunction()
{
Console.WriteLine("Scheduler is initiated !\n\n");
bool bSuccess = false;
Console.WriteLine("Got ActiveBuses and coresponding Paths!\n\n");
List<ActiveBusAndItsPathInfo> ActiveBusAndItsPathInfoList = BusinessLayer.GetActiveBusAndItsPathInfoList();
if (ActiveBusAndItsPathInfoList != null)
{
Thread[] threads = new Thread[ActiveBusAndItsPathInfoList.Count];
while (true)
{
foreach (ActiveBusAndItsPathInfo ActiveBusAndItsPathInfoObj in ActiveBusAndItsPathInfoList)
{
//Get curent time
//compare for time difference less than equal to 5 mins
if (ActiveBusAndItsPathInfoObj.isSMSThreadActive == false)
{
// Console.WriteLine("SMS Thread about to initiate!\n\n");
DateTime CurrentTime = System.DateTime.Now;
// TimeSpan CurrentTimespan = (TimeSpan)CurrentTime;
DateTime Bustime = Convert.ToDateTime(ActiveBusAndItsPathInfoObj.busObj.Timing);
//TimeSpan BustimeTimes = Bustime.TimeOfDay;
TimeSpan tsa = Bustime - CurrentTime;
// if(tsa.TotalMinutes > 0 && tsa.TotalMinutes < 5)
{
ActiveBusAndItsPathInfoObj.isSMSThreadActive = true;
***ThreadStart starter = delegate { SMSThreadEntryPointFunction(ActiveBusAndItsPathInfoObj); };
Thread t = new Thread(starter);
**// t.Start();
int indexOfCurrentActiveBusAndItsPathInfoObj = ActiveBusAndItsPathInfoList.IndexOf(ActiveBusAndItsPathInfoObj);
threads[indexOfCurrentActiveBusAndItsPathInfoObj] = new Thread(starter);
threads[indexOfCurrentActiveBusAndItsPathInfoObj].Start();
threads[indexOfCurrentActiveBusAndItsPathInfoObj].Join();***
}
}
}**
}
}
return bSuccess;
}
ode here
New Code:-
Still giving synchronization issue...
foreach (ActiveBusAndItsPathInfo ActiveBusAndItsPathInfoObj in ActiveBusAndItsPathInfoList)
{
//Get curent time
//compare for time difference less than equal to 5 mins
if (ActiveBusAndItsPathInfoObj.isSMSThreadActive == false)
{
DateTime CurrentTime = System.DateTime.Now;
DateTime Bustime = Convert.ToDateTime(ActiveBusAndItsPathInfoObj.busObj.Timing);
TimeSpan tsa = Bustime - CurrentTime;
if(tsa.TotalMinutes > 0 && tsa.TotalMinutes < 5)
{
ActiveBusAndItsPathInfoObj.isSMSThreadActive = true;
ThreadPool.QueueUserWorkItem(state => SMSThreadEntryPointFunction(ActiveBusAndItsPathInfoObj)
}
}
}
}
return bSuccess;
}
do i have to lock my method ...SMSThreadEntryPointFunction(ActiveBusAndItsPathInfoObj)
currently i am trying
ThreadPool.QueueUserWorkItem(new WaitCallback(SMSThreadEntryPointFunction), (object)ActiveBusAndItsPathInfoObj);
but giving an error:-"No overload for SMSThreadEntryPointFunction matches delegate system.thread.WaitCallback"
(Any One There)
ThreadPool.QueueUserWorkItem(state => MyMethod(bus1));
ThreadPool.QueueUserWorkItem(state => MyMethod(bus2));
...
The reason that you find your threads not executing in parallel is the line:
threads[indexOfCurrentActiveBusAndItsPathInfoObj].Join();
This causes the main thread to wait for the current bus thread to finish before the main thread continues. You may want to move the Join() call outside the loop that starts your threads or eliminate it all together. Start by commenting it out so you can see the effect it has.
Getting multithreaded code to work correctly can be challenging; and probably impossible if you don't have a good understanding of what's going on. I second Darin's suggestion that you read through the tutorial
Finally, it looks like what you're trying to do is run a simulation. A much simpler approach to this is to set up a priority queue of events ordered by simulation time. The main loop then simply pulls the first event off the queue, updates the simulated time to the event's time, and executes the event. Event handlers can schedule future events by pushing them on to the queue. You can find more about this idea by searching for information on "discrete event simulation".
You need to use a BackgroundWorker for your method and each method needs to run in it's own thread. So you'll have to assign each method it's own backgroundworker. You need to make sure that any resources that could be accessed by muyltiple threads at once are locked appropriately so that things are thread-safe.
Thread-safety means that multiple threads can use a resource with incurring data corruption or creating race conditions and/or deadlocks.
Related
I'm currently using a stopwatch as a global timer. I have main thread running, another thread, and an event method.
The main thread launches the other thread and the event method is triggered by events. Both methods will call the stopwatch and get its time. The thing is, the times are not consistent:
from main thread:
START REC AT 9282
STOp REC AT 19290
from another thread:
audio 1
audio 304
audio 354
audio 404
audio 444
audio 494
audio 544
audio 594
from event method:
video 4
video 5
video 29
video 61
video 97
video 129
video 161
I don't get why if i start my rec at 9282, the other two functions that call the stopwatch will have timers that start at zero? Is this a thread related issue? How can i fix this? Thanks
UPDATE:*********
when i save my frames i changed to:
long a = relogio.EllapseMilliseconds
i print out this value and its ok, as expected. but when i print the value stored in the lists, they come as starting from the beggining. strange huh?
SORRY FOR ALL THE TROUBLE, I PRINTED IT WITHOUT THE STARTING TIME,THATS WHY THEY ALL SEEMED TO START FROM ZERO! MANY THANKS AND SORRY!
main thread
private void Start_Recording_Click(object sender, RoutedEventArgs e)
{
rec_starting_time = relogio.ElapsedMilliseconds;
Console.WriteLine("START REC AT " + rec_starting_time);
write_stream.enableRecording();
Thread a = new Thread(scheduleAudioVideoFramePicks);
a.Start();
scheduleAudioVideoFramePicks - this thread just counts the time, so i know when to stop
//while....
if (rec_starting_time + time_Actual > rec_starting_time+recording_time * 1000)//1000 - 1s = 1000ms
{
totalRecordingTimeElapsed = true;
write_stream.disableRecording();
Console.WriteLine("STOp REC AT " + relogio.ElapsedMilliseconds);
}
//end while
lock (list_audio)
{
int b = 0;
//print time of frames gathered
foreach(AudioFrame item in list_audio){
Console.WriteLine("audio " + (item.getTime() - rec_starting_time));
}
lock (list_video)
{
}
foreach (VideoFrame item in list_video)
{
Console.WriteLine("video " + (item.getTime() - rec_starting_time));
}
}
the another thread, where i get the time
if (write_stream.isRecording())
{
list_audio.Enqueue(new AudioFrame(relogio.ElapsedMilliseconds, audioBuffer));
}
event method
if (write_stream.isRecording())
{
list_video.Add(new VideoFrame(relogio.ElapsedMilliseconds, this.colorPixels));
}~
i dont know if this is relevant, but i start my stopwatch like this
public MainWindow()
{
InitializeComponent();
//some code
this.relogio = new Stopwatch();
relogio.Start();
}
Stopwatch is not threadsafe, particularly for 32-bit programs.
It uses the Windows API call QueryPerformanceCounter() to update a private long field. On 32-bit systems you could get a "torn read" when one thread reads the long value while another thread is updating it.
To fix that, you'd have to put a lock around access to the Stopwatch.
Also note that one some older systems there were bugs where inconsistent values could be returned from different threads calling QueryPerformanceCounter(). From the documentation:
On a multiprocessor computer, it should not matter which processor is called. However, you can get different results on different processors due to bugs in the basic input/output system (BIOS) or the hardware abstraction layer (HAL). To specify processor affinity for a thread, use the SetThreadAffinityMask function.
I have never encountered this bug myself, and I don't think it's very common.
What results do you get with the following test program? The times should be mostly increasing in value, but you are liable to get one or two out of order just because their threads get rescheduled just after they've read a value and before they add it to the queue.
namespace Demo
{
class Program
{
Stopwatch sw = Stopwatch.StartNew();
object locker = new object();
ConcurrentQueue<long> queue = new ConcurrentQueue<long>();
Barrier barrier = new Barrier(9);
void run()
{
Console.WriteLine("Starting");
for (int i = 0; i < 8; ++i)
Task.Run(()=>test());
barrier.SignalAndWait(); // Make sure all threads start "simultaneously"
Thread.Sleep(2000); // Plenty of time for all the threads to finish.
Console.WriteLine("Stopped");
foreach (var elapsed in queue)
Console.WriteLine(elapsed);
Console.ReadLine();
}
void test()
{
barrier.SignalAndWait(); // Make sure all threads start "simultaneously".
for (int i = 0; i < 10; ++i)
queue.Enqueue(elapsed());
}
long elapsed()
{
lock (locker)
{
return sw.ElapsedTicks;
}
}
static void Main()
{
new Program().run();
}
}
}
Having said all that, the most obvious answer is that in fact you aren't sharing a single Stopwatch between the threads, but instead you have accidentally started a new one for each thread...
Let us consider a method which changes the string contains value often .
I need to create thread which runs for every 1 min for getting a values from a string .
Is it possible?
I have tried following code which sleeps the entire process other that particular thread:
System.Threading.Thread.Sleep(10000);
If you wand to run a threaded process at a defined period of time the System.Threading.Timer class will be perfect
var timer = new System.Threading.Timer((o) =>
{
// do stuff every minute(60000ms)
}, null, 0, 60000);
However if you are updating any UI code from this thread dont forget to invoke back on the UI thread
WPF:
var timer = new System.Threading.Timer((o) =>
{
Dispatcher.Invoke(DispatcherPriority.Normal, (Action)delegate
{
// do stuff WPF UI safe
});
}, null, 0, 60000);
Winform
var timer = new System.Threading.Timer((o) =>
{
base.Invoke((Action)delegate
{
// do stuff Winforms UI safe
});
}, null, 0, 60000);
Example:
private void StartUpdateTimer()
{
var timer = new System.Threading.Timer((o) =>
{
string ss = "gowtham " + DateTime.Now.ToString();
Response.Write(ss);
}, null, 0,1000);
}
Sleep does not start new thread, it blocks current thread (in your case UI thread) for given number of milliseconds.
Based on your description you want to start new thread and can sleep in that thread. Also it may be easier to use timers. Complete sample and information on Thread object avaialbe in MSDN Thread article:
new Thread(ThreadFunction).Start();
Use:
new Thread(delegate()
{
while(true)
{
// Do stuff
Thread.sleep(60000);
}
}).Start();
60 000 miliseconds is a minute
Thread.sleep puts the current thread to sleep
C# or more spesificly .NET supports MULTITHREADING.
when you use Thread.Sleep() it will disable the one thread that used Thread.Sleep()
here is an exmaple of using the 'TPL' to lunch athread that samples the string every 60 seconds
System.Threading.Tasks.Task.Factory.StartNew(
()=>
{
System.Threading.Thread.Sleep(60000);
ReadString()}
)
you should keep in mind that you need to protect your string from RACE CONDITION
use C# lock for this
Instead of starting a new thread every 60 seconds, use one thread, that sleeps after finishing until the next run. Something like this:
Class Main{
public void startObserverThread(){
Thread t = new Thread(this.observerThread);
t.start();
}
private DateTime lastRun = null;
public void observerThread(){
if (lastRun == null || DateTime.Now.Subtract(lastRun).Seconds >= 60){
lastRun = DateTime.Now;
//do thread work.
}else{
//check every second, if time elapsed
Thread.sleep(1000);
}
}
}
Change the waiting time if it needs to be more accurate.
The big advantage vs resheduling a new thread at the end of the thread is, that you dont need to take care about the execution time of the task itself. If it takes 10 seconds, the thread will sleep for like 50 seconds. if it takes 50 seconds, the thread only sleeps 10 seconds after completing the task work.
I have a logical problem i am not sure how to solve.. Basically i have a program that starts threads based on a numericUpDown value, if the user selects 5 in the numericUpDown box 5 threads will start.
The problem is that the user also has a listbox they can fill in with info, which will be used in the threads..
So what i want to be able to do in my loop instead of looping it 5 times from the numericUpDown value is if; lets say the user enteres 10 items in the listBox, and selects to use 5 threads.. i then want all the listBox items to be queued but only have 5 run at a time..
How would i accomplish this?
Oh if it matters this is how i start my threads:
Thread thread = new Thread(() => doTask(numeret));
thread.IsBackground = true;
thread.Start();
I believe you wish to use a ThreadPool, as explained here:
http://msdn.microsoft.com/en-us/library/system.threading.threadpool.aspx
You need to specify the number of threads to use, and then use ThreadPool.QueueUserWorkItem to queue your tasks.
Alternatively, you can use the parallel extensions to LinQ to perform asynchronous tasks (not the same as multithreading) - and specify the .MaxDegreesOfParalallism() value (which only sets the upper maximum)
itemsToProcess.AsParallel().MaxDegreesOfParalallism(numThreads).ForAll(item =>
{
doTask(item);
});
Usually, something like this is done using worker threads. You create a list of work items (= your listbox entries):
List<WorkItem> myWorkItems = ...; // contains 10 items
And you create your threads. You do not, however, assign a work item to the thread yet (as you do in your example):
for (int i = 0; i < numberOfThreads; i++) { // creates 5 threads
var t = new Thread(doWork);
t.IsBackground = true;
t.Start();
}
Each thread runs a loop, checking for new work items (thread-safe!) and doing work, until no more work is to be done:
void doWork() {
while (true) {
WorkItem item;
lock(someSharedLockObject) {
if (myWorkItems.Count == 0)
break; // no more work to be done
item = myWorkItems[0];
myWorkItems.Remove(item);
}
doTask(item);
}
}
This is similar to what the ThreadPool of the .net Framework does. The ThreadPool, however, is designed to work best when the number of threads can be chosen be the Framework. The example above gives you full control over the number of threads (which seems to be what you want).
Store the info from the listbox in a stack (for example).
Then, in the doTask() method : pop an element from the stack, do the stuff and do it again until the stack is empty.
Basically :
//Stack containing the info to process
Stack<string> infos = new Stack<string>();
//Method for the thread
void doTask()
{
while(true)
{
string info;
//Threadsafe access to the stack
lock (infos.SyncRoot)
{
//Exit the thread if no longer info to process
if (infos.Count == 0) return;
info = infos.Pop();
}
//Do the actual stuff on the info
__DoStuff(info);
}
}
I have a requirement for a timer that has the following behaviour:
Millisecond accuracy
I want the tick event handler to only be called once the current tick handler has completed (much like the winforms timer)
I want exceptions on the main UI thread not to be swallowed up by the thread timer so this requires Invoke/Send instead of BeginInvoke/Post
I've played around with CreateTimerQueueTimer and had some success but at the same time had problems with code reentrance and/or locks when deleting the timer.
I decided to create my own timer so that I could get a better idea of what is going on under the hood so that I can fix the locking and reentrance problems. My code seems to work fine leading me to believe that I may as well use it. Does it look sound?
I've put in a check if the timer is deleted to make sure that the deletion is complete before the timer can be created again. Does that look ok?
Note: I should say that I call timeBeginPeriod(1) and timeEndPeriod(1) inorder to achieve the millisecond accuracy.
(The following code is converted from vb.net to c#, so apologies for any missed mess-ups}
ETA: I've found a problem with it. If the timer is running at an interval of 1 millisecond, and I call, say, Change(300), it locks up # while (this.DeleteRequest). This
must be because the TimerLoop is in the this.CallbackDelegate.Invoke(null) call.
public class MyTimer : IDisposable
{
private System.Threading.TimerCallback CallbackDelegate;
private bool DeleteRequest;
private System.Threading.Thread MainThread;
public MyTimer(System.Threading.TimerCallback callBack)
{
this.CallbackDelegate = callBack;
}
public void Create(int interval)
{
while (this.DeleteRequest) {
System.Threading.Thread.Sleep(0);
}
if (this.MainThread != null) {
throw new Exception("");
}
this.MainThread = new System.Threading.Thread(TimerLoop);
// Make sure the thread is automatically killed when the app is closed.
this.MainThread.IsBackground = true;
this.MainThread.Start(interval);
}
public void Change(int interval)
{
// A lock required here?
if (!this.IsRunning()) {
throw new Exception("");
}
this.Delete();
this.Create(interval);
}
public void Delete()
{
this.DeleteRequest = true;
}
public bool IsRunning()
{
return (this.MainThread != null) && this.MainThread.IsAlive;
}
private void TimerLoop(object args)
{
int interval = (int)args;
Stopwatch sw = new Stopwatch();
sw.Start();
do {
if (this.DeleteRequest) {
this.MainThread = null;
this.DeleteRequest = false;
return;
}
long t1 = sw.ElapsedMilliseconds;
// I want to wait until the operation completes, so I use Invoke.
this.CallbackDelegate.Invoke(null);
if (this.DeleteRequest) {
this.MainThread = null;
this.DeleteRequest = false;
return;
}
long t2 = sw.ElapsedMilliseconds;
int temp = Convert.ToInt32(Math.Max(interval - (t2 - t1), 0));
sw.Reset();
if (temp > 0) {
System.Threading.Thread.Sleep(temp);
}
sw.Start();
} while (true);
}
// The dispose method calls this.Delete()
}
I would recommend using p/Invoke and using the timers from Win32's Timer Queues:
http://msdn.microsoft.com/en-us/library/ms686796(v=vs.85).aspx
One should be mindful that the managed CLR environment has a lot of non-determinism built into it, garbage collection, for instance. Just because your timer is has a period of 1 millisecond doesn't mean that that is necessarily what happens.
Also, the documentation doesn't mention it, but the callback invoked by the timer must be pinned in memory and not garbage collectable, via a GCHandle or other construct. When a timer (or timers, if you kill off a timer queue), the callback will be executed one last time. Not sure whether that happens by the internal wait expiring, or by signalling the internal event handle.
Execution of DeleteTimerQueueTimer() and DeleteTimerQueueEx() can be made synchronous, so they won't return until all timers have signalled and invoked their last callback, but doing that would be suboptimal.
If you don't pin the callbacks and prevent them from being garbage-collected, things will go swimmingly...most of the time. You'll encounter random exceptions.
Also, the callback should be smart enough to bail out if the timer is being deleted, lest it make reference to something that's already GC'd.
μTimer would be a better example!
You can find it here # https://stackoverflow.com/questions/15725711/obtaining-microsecond-precision-using-net-without-platform-invoke?noredirect=1#comment22341931_15725711
It provides accurate wait times down to 1µs and possibly lower depending on your NIC!
Let me know if you need anything else!
I have asked this question before - but I have spent some time thinking about it and have implemented a working version.
Overview
1) Threads are being created to perform a certain task.
2) Only one thread can perform the task at a time.
3) Each thread performs the exact same task. (Does a bunch of checks and validations on a system)
3) The threads are being created faster than the task can be performed. (I have no control over the thread creation)
Result is that overtime I get a backlog of threads to perform the task.
What I have implemented goes as follows
1) Thread checks to see how many active threads there are.
2) If there are 0 threads it is marked to PerformTask and it starts the task
3) If there is 1 thread it is marked to PerformTak and it blocks
4) If there is more than 1 thread the thread is not marked to PerformTasks and just dies
The idea is that if there is a thread waiting to perform the task already I just kill the thread.
Here is the code that I came up with
bool tvPerformTask = false;
ivNumberOfProcessesSemaphore.WaitOne();
if (ivNumberOfProcessesWaiting == 0 ||
ivNumberOfProcessesWaiting == 1)
{
ivNumberOfProcessesWaiting++;
tvPerformTask = true;
}
ivNumberOfProcessesSemaphore.Release();
if (tvPerformTask)
{
//Here we perform the work
ivProcessSemaphore.WaitOne();
//Thread save
ivProcessSemaphore.Release();
ivNumberOfProcessesSemaphore.WaitOne();
ivNumberOfProcessesWaiting--;
ivNumberOfProcessesSemaphore.Release();
}
else
{
//we just let the thread die
}
The problem that I have is not that it doesn't work it is just that I do not find the code elegant specifically I am not very happy that I need 2 semaphores an integer and a local flag to control it all. If there a way to implement this or pattern that would make the code simpler.
How about this?
private readonly _lock = new object();
private readonly _semaphore = new Semaphore(2, 2);
private void DoWork()
{
if (_semaphore.WaitOne(0))
{
try
{
lock (_lock)
{
// ...
}
}
finally
{
_semaphore.Release();
}
}
}
Consider using a ThreadPool instead of trying to managing the creation and destruction of individual threads on your own.