It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
In many programming languages, many questions have been raised to stop execution of a thread.In c/c++ goto is still used, where as in Java , goto is not used,but still it's reserved; stop(), stop(Throwable) and suspend(), destroy() and resume(), which were intended to provide the basic functionality for starting and stopping a thread has been depreciated.
Can we use goto to simply to move out of a thread?
Somethig like this :
//Thread block
{...
if(some condition)
goto out;
.....
...
}//thread block over
out:
// I am out!!
}
I know using goto is a very very bad practice, but can still it be used like this?
UPDATE:
Or:
//Thread block
{...
if(some condition)
goto out;
.....
...
out:
// I am out!!
}//thread block over
From the comments,is this the solution?
UPDATE2:
Well,I am getting mix kind of answers.Some yes,some no.I don't use c/c++ much ,otherwise could have implemented and see myself.
This doesn't work.
You can't goto to another method.
A thread is not bound to a method and one method can be executed by multiple threads.
If the goto location would be in the same method, the execution would simply continue at the new location in the thread that executed the goto statement.
What you can do, is go to the end of the thread method - if the current code is in that method. This won't end the thread, but the goto will move the program flow just before the end of the thread method which will lead to the thread method being finished executing and thus ending the thread.
This is the same effect as simply returning from the thread method.
Absolutely, you can: you can use goto to transfer control unconditionally to the end of your method from almost anywhere, with very few restrictions. If this is the method that implements your thread, it will exit, ending the thread.
Whether you should is a different question: with very few exceptions, goto makes your program less readable; without exceptions, you can achieve the same result without a goto, and improve readability at the same time. For example, you could use return to end the method implementing the logic of your thread.
You can't "move out" of a thread using goto. A thread's execution is not limited to a given scope and just moving to another location in your code will not terminate it.
You can not goto to a label out of the your thread function
You can set the out: at the end of the thread functio. And in this way if you want to stop your thread you can goto the out: (from any place in your thread function) and the thread function will be stopped
If you want to execute some part of your code at the end of your thread you can use pthread_cond_signal(&cond);
the following link contains an example of how to use it: multithread launching order
No you can't.
But perhaps you don't need to... You can try to use ThreadAbortException (by calling Thread.Abort()) and catch it (yes, within the thread), executing the 'out' functionality, and do a Thread.ResetAbort. Just be careful and be sure to read up on the risks involved on MSDN when calling abort from another thread (which you don't seem to be doing).
See also: http://msdn.microsoft.com/en-us/library/ty8d3wta.aspx
First of all, putting cleanup code at end of function, and jumping to it with goto is quite valid pattern in C. Use it when ever it makes the code cleaner and easier to understand. Of course it can be abused, and it doesn't work that well when you have multiple levels of functions, so it might encourage making too long functions just to be able to goto to cleanup code. But as long as it's used carefully, goto is quite valid in C. Also, since the question is a bit vague, better say this explicitly: you can not goto between functions. And in languages supporting exceptions, you should use those instead of goto (of course you have to use them right too, not abuse them).
But often, especially with threads, it is better to register cleanup handlers for the thread, so you can then just return or call the thread frameworks "exit this thread" function, instead of using goto to cleanup code.
Finally, with the code above, with no code after out: label, you could just return instead of using goto... This assumes you are using a threading library, which takes a function to run in other thread, and will end the thread when that function returns.
Related
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 9 years ago.
call a function continuously in c# console application. without using infinite loop and recursion because if use those then cpu usage is more.please can any one help me to solve this problem.some one suggest me to use background thread, but it doesn't call the function continuously.
Thread th = new Thread(//fun);
th.IsBackground = true;
th.start();
Use a system timer with a short interval.
In the "tick" event of the timer:
Stop the timer
Call the function
Restart the timer
A system timer's event runs on a thread pool thread so your console app thread continues as normal. The function is run as frequently as the interval allows, for the duration of the application. No recursion. No infinite loops.
If you want to call it continuously, then a high CPU usage is necessary: because the CPU is always busy doing what you want.
If you want to have a lower cpu usage, then you cannot run your function continuously but only at a (possibly very small) interval.
You have to decide.
You can use the Thread code but a thread just effectively calls the function which means that your function needs to be recursive or that it needs to have an infinite loop.
public void StartThread()
{
Thread th = new Thread(function);
th.IsBackground = true;
th.start();
}
public void function()
{
//preferably have some way of killing this if needs be so don't necessarily use 'true'
while(true)
{
//do stuff
//sleep an appropriate amount of time to not overload the cpu
//This sleeps (basically pauses thread) for 10 milliseconds
Thread.Sleep(10);
}
}
Adding the Thread.Sleep will stop the overloading of the CPU which you were referring to. Just run sleep for an amount of time which is acceptable for your application. If it's updating a value on a GUI then the user won't really notice if the value gets updated every half second (Thread.Sleep(500)) or every milliseconds (Thread.Sleep(1))
I'm not sure I get your answer, but let me explain how a thread works.
Threads
Threading, in most programming languages, is the practice of effectively splitting up execution, into synchronous execution. What this means, is that two methods can run at the same time.
Common uses of a Thread
One example of the use of a thread, is to listen for incoming connections on a server. So you'd have a thread, something like:
while(true)
{
// Listen to incoming messages.
}
The infinite loop is because, at no point, do you want to stop listening for incoming messages. That is the role of the server; to manage connections. However, the thread is killed when the program execution finishes. The reason why this is considered common practice is, because of the fact that this is run on a separate thread, it doesn't impact performance as much as you might think. C# is very good at dealing with multiple threads; as are most languages.
Alternatives
Well, look at it like this. If you want to listen for 1000 cycles, then you will do something like:
while(count < 1000)
{
count++;
// Do some thread code.
}
It really depends on what you want the thread for, that defines the code that goes into the thread, and how long it will run for.
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
Edit a few years on: this was clearly a terrible approach, at the start of me using C#/.NET. Hopefully this question helps another noob with the same "problem".
Is this the best way to approach this scenario?
while(true)
{
if(Main.ActiveForm != null)
{
Main.ActiveForm.Invoke(new MethodInvoker(Main.SomeMethod));
break;
}
}
This is performed on a second thread.
Is this the best way to approach this scenario?
Just to clarify, the scenario is "I have a property of reference type; as soon as the property is not null I wish to invoke one of its methods", and the technique is "spin up another thread, busy-wait until the value is not null, invoke, and stop waiting".
The answer to your question is no, this is not the best way to approach this scenario. This is a terrible way to solve this problem for several reasons.
First, the code is simply wrong. The C# language makes no guarantee that this code works. If it works, then it is working by accident, and it can stop working at any time.
There are three reasons that this code is wrong.
The first reason it is wrong is because of the way threads work on modern operating systems. It is possible that the two threads are each assigned to their own processor. When a processor accesses memory on a modern machine, it does not go out to main memory every time. Rather, it fetches hundreds or thousands of nearby values into a cache the first time you hit an address. From then on, it accesses the local cache rather than taking the expensive bus ride back to main memory. The implications of that should be obvious: if one thread is writing and another thread is reading, then one thread might be writing to one processor cache and the other might be reading from an entirely different processor cache. They can be inconsistent forever if nothing forces them to be consistent, and therefore your loop can run forever even if the property has been set on another thread.
(And the "backwards" case is also possible; if the value of the property is now null, and was set at some time in the past, then it is possible that the second thread is reading the old, stale value and not the fresh null value. It therefore could decide to not wait at all, and invoke the method on a stale value of the property.)
The second reason this code is wrong is because it has a race condition. Suppose someone assigns the property to non-null on thread one, and then thread two reads it as non-null so you enter the body of the "if", and then thread three assigns it back to null, and then thread two reads it as null and crashes.
The third reason this code is wrong is because the compiler -- either the C# compiler or the jitter -- is permitted to "optimize" it so that it stays in the loop forever without doing the test a second time. The optimizer is allowed to analyze the code and realize that after the first time through the loop, if the test fails then nothing in the rest of the loop can cause it to succeed. It is permitted to then skip the test the next time through because it "knows" that it cannot succeed. Remember, the optimizer is permitted to make any optimization that would be invisible in a single-threaded program.
The optimizer does not actually make this optimization (to my knowledge) but it is permitted to, and a future version could do so. The optimizer can and does make similar optimizations in similar situations.
In order to make this code correct there must be a memory barrier in place. The most common technique for introducing a barrier is to make the access "volatile". The memory barrier forces the processor to abandon its cache and go back to main memory, and discourages the compiler from making aggressive optimizations. Of course, properties may not be volatile, and this technique utterly wrecks performance because it eliminates the one of the most important optimizations in modern processors. You might as well be accessing main memory by carrier pigeon, the cost is so onerous compared to hitting the cache.
Second, the code is bad because you are burning an entire processor sitting there in a tight loop checking a property. Imagine a processor is a car. Maybe your business owns four cars. You are taking one of them and driving it around the block non-stop, at high speed, until the mailman arrives. That is a waste of a valuable resource! It will make the entire machine less responsive, on laptops it will chew through battery like there is no tomorrow, it'll create waste heat, it's just bad.
I note however that at least you are marshalling the cross-thread call back to the UI thread, which is correct.
The best way to solve this problem is to not solve it. If you need something to happen when a property becomes non-null, then the best solution is to handle a change event associated with that property.
If you cannot do that then the best solution is to make the action the responsibility of the property. Change the setter so that it does the action when it is set to non-null.
If you can't make it the responsibility of the property, then make it the responsibility of the user who is setting the property. Require that every time the property be set to non-null, that the action be performed.
If you can't do that then the safest way to solve this problem is to NOT spin up another thread. Instead, spin up a timer that signals the main thread every half second or so, and have the timer event handler do the check and perform the action.
Busy-waiting is almost always the wrong solution.
All you need to do is attach an event handler to the Activated event of your form. Add the following inside that form's constructor:
Activated += SomeMethod;
And it will be fired whenever you re-activate the form after previously using another application.
The primary advantage of this approach is that you avoid creating a new thread just to have it sitting around doing a spinwait (using up a lot of CPU cycles).
If you want to use this approach, note that you have a race condition: someone else might set Main.ActiveForm to null between your test and your Invoke() call. That would result in an exception.
Copy the variable locally before doing any tests to make sure that the variable cannot be made null.
while(true)
{
var form = Main.ActiveForm;
if(form != null)
{
form.Invoke(new MethodInvoker(Main.SomeMethod));
break;
}
}
When you use a loop You are waste CPU.
The beter way to do this is use events:
// make event object in some shared place
var ev = new ManualResetEvent(false);
// do when form loaded
ev.Set();
// wait in thread
ev.WaitOne();
use :
while(Main.ActiveForm == null) { }
I would do it like that.
while(Main.ActiveForm == null)
{
//maybe a sleep here ?!
}
Main.ActiveForm.Invoke(new MethodInvoker(Main.SomeMethod));
Refer the thread-safe call tutorial at MSDN, have a look at following statments:
// InvokeRequired required compares the thread ID of the
// calling thread to the thread ID of the creating thread.
// If these threads are different, it returns true.
if (this.textBox1.InvokeRequired) {
SetTextCallback d = new SetTextCallback(SetText);
this.Invoke(d, new object[] { text });
} else {
this.textBox1.Text = text;
}
Of course, I've used it many times in my codes, and understand a little why to use it.
But I still have some unclear questions about those statements, so anybody help me to find them out, please.
The questions are:
Will the code can run correctly with the statements in the if body only? I tried and seems it just cause the problem if the control is not initialize completely. I don't know is there more problem?
Which the advantage of calling method directly (else body) instance via invoker? Does it save resource (CPU, RAM) or something?
Thanks!
You can of course always call using the Invoker, but:
It usually makes the code more verbose and difficult to read.
It is less efficient as there are several extra layers to contend with (setting up delegates, calling the dispatcher and so on).
If you are sure you'll always be on the GUI thread, you can just ignore the above checks and call directly.
If you always run just the first part of the if statement, it will always be fine, as Invoke already checks if you're on the UI thread.
The reason you don't want to do this is that Invoke has to do a a lot of work to run your method, even if you're already on the right thread. Here's what it has to do (extracted from the source of Control.cs):
Find the marshaling control via an upward traversal of the parent control chain
Check if the control is an ActiveX control and, if so, demand unmanaged code permissions
Work out if the call needs to be invoked asynchronously to avoid potential deadlock
Take a copy of the calling thread's execution context so the same security permissions will be used when the delegate is finally called
Enqueue the method call, then post a message to invoke the method, then wait (if synchronous) until it completes
None of the steps in the second branch are required during a direct call from the UI thread, as all the preconditions are already guaranteed, so it's definitely going to be faster, although to be fair, unless you're updating controls very frequently, you're very unlikely to notice any difference.
I'm reading through Constrained Execution Regions and other errata [Brian Grunkemeyer] in an attempt to understand constrained execution regions, however I'm having some problems understanding the following sample:
RuntimeHelpers.PrepareConstrainedRegions();
try {
// Prepare my backout code
MethodInfo m = _list.GetType().GetMethod("RemoveAt", new Type[] { typeof(int) });
RuntimeHelpers.PrepareMethod(m.MethodHandle);
IEnumerator en = c.GetEnumerator();
while(en.MoveNext()) {
_list.Insert(index++, en.Current);
// Assuming that these lines aren't reordered.
numAdded++;
}
_version++;
}
catch(Exception) {
// Reliable backout code
while(numAdded > 0) {
_list.RemoveAt(index--);
numAdded--;
}
throw;
}
My understanding is that the try block is not constrained, only the finally and catch blocks are constrained. This means that during the try block an asynchronous exception (e.g. ThreadAbortException) can be thrown at any time, in particular it could be thrown before numAdded++ but after _list.Insert. In this case the backout code would remove one item too few from _list.
Given this I'm struggling to understand the purpose of the constrained execution region in this example.
Is my understanding of this correct or have I missed something?
The documentation and the actual behavior of CERs do not match exactly based on what I observe. The issue you describe where a ThreadAbortException gets injected between Insert and numAdded++ is not possible with any of the .NET Framework versions I have tested. There are two possible reasons for this.
PrepareConstrainedRegions does, despite what the documentation says, have an observable effect on the try block. It will delay certain abort injections; specifically those that do not come while the thread is in an alertable state.
Even in the absence of the PrepareConstrainedRegions call the abort still will not get injected into that location. Based on the SSCLI code the abort will be injected at the backward jump to spin the while loop.
I figured some of this out while answering my own related question here and then attempting to answer a question about how Thread.Abort actually works here.
Point #2 is not legit. It is an implementation detail of the SSCLI that may not carry over to the official distributions (though I suspect it actually does). Furthermore, it ignores the possibility of having the abort injected at some point during the execution of Insert. I suppose it is possible that the crucial bits of Insert could use a CER internally though.
Point #1 may be the one that matters, but that begs the questions why did Microsoft not document it and why did the article you cited not mention it either. Surely the author of the article knew of this fact. Otherwise, I too am not understanding how the code presented could possibly be safe. In other words, it seems safe only by accident right now.
If I had to take a guess as to what PrepareConstrainedRegions is doing behind the scenes I would say that it sets a flag in the JIT engine that tells it not to inject the GC poll hook that gets placed strategically at backward branch jumps for code inside a CER try block. This GC poll hook is where the asynchronous abort would typically be injected (in addition to its main purpose related to garbage collection).
In my apps i find the need to have infinite while loops mostly to do some repeated action continuosly unless another event takes place so what i am doing is
while(chkFlag)
{
//do something here which takes around 30 seconds
}
Then in some other event say a button press to stop the loop i do
chkFlag = false;
Now this does the work but the problem is this does not stop the loop instantaneously as the chkFlag is checked only after the complete execution of the loop takes place. So can anybody please tell me how i can exit a loop instantaneouly based on an event.
The "blocking" code should likely be moved into some kind of worker thread (which can be terminated and/or have the results discarded). If using a BackgroundWorker (recommended, as it makes this simple), there is built-in support to handle a cancel operation.
Then the loop can either be moved inside the BackgroundWorker or the completion (RunWorkerCompleted) event of the worker can trigger the next worker to start (which causes an implicit loop).
Happy coding.
There are more "aggressive" ways of terminating/signaling a thread; but suggesting these would require more information than present.
you can't make it exit instantly (well, you could run the loop in a new thread and Abort it, if it's really safe to have an exception thrown from it at any time), but you could scatter if(!chkFlag) break; at various points within the loop that it's safe to exit. The usual method of doing this is to use a BackgroundWorker or a CancellationToken rather than a simple boolean flag.
Of course, it will still need to be run in another thread so that the button event can run at all. BackgroundWorker will take care of this automatically.
You are looking for break;.
I suppose, based on the anonymous downvoter, I should elaborate. The syntax above will immediately exit the loop that you are in (it works in the other loops as well; it's probably worth noting that continue exists to restart the loop at the beginning, which will perform increment logic in for-style loops).
How you decide to execute break is up to you, but it must be within the loop itself.
There are multiple approaches to this, such as placing checks for the event within the loop and calling break; if it occurs. Others have noted the other approaches with BackgroundWorkers and Cancel Tokens (this is preferred given it's not within the loop).
Is it possible you want to use a new thread? What are you doing for 30 seconds in the loop. Sounds like maybe there's a better design to use.
Have you considered using a timer, or setting up an event handler?