C# Thread.Start life cycle - multithreading

I have a question about the lifecycle of a thread when i use Thread.Start, for example if a do a foreach loop like this one:
foreach(var item in MyList)
{
var t = new Thread(ProcessRequest);
t.Start(item);
}
private void ProcessRequest(ListItem item)
{
//do something
}
In this case it will exists N Threads, so what is the lifecycle of all these?
I will appreciate your explanation

Each thread exists until it's ProcessRequest is finished. Once the method returns the thread is returned to the threadpool to be used again.
Even though you are not maintaining a reference to the thread object it's referenced by the framework and the OS so it won't get freed up until the thread is finished running at a minimum.

Related

why synchronized object can still be manipulated

Code snippet like below:
List<String> list = new ArrayList<>();
public void addValue(int i) {
synchronized (list) {
list.add("list" + i);
}
}
My question is that what is locked by keyword synchronized.
What will be checked of the list when two threads are asking to execute the code block?
The same question is that I synchronized this but its fields can still be changed.
The synchronized block is locked. When the code runs, a thread does not lock the object, instead, it OBTAINS the lock of the list object,(which is a mark word inside the object header) so other thread cannot obtain the same lock. As a result, the code inside the block can only be executed by one thread at the same time.

Qt code sequence in multithread. Is this possible?

This is objectA which subclass QThread
void run()
{
while (continue)
emit query();
}
void work(int input, bool workdone)
{
// work hard here
if (workdone) { continue = false; }
}
This is some code in main object
{
ObjectA A* = new ObjectA(this);
connect(A, SIGNAL(query()), this, SLOT(handleQuery()));
objectA.start();
}
void handleQuery()
{
A.work(interger, allJobDONE);
}
OK, I don't know how to name the question. Basically, it is just "will this code work?" If yes, how would be the code sequence?
Let me explain my question. ObjectA is a thread. It is going to query information from time to time by emitting a query signal. When the query signal is grubbed by the main code, the main code decide whether there is job so as to send the job to ObjectA by calling work() function.
If this code works, both the run() and the work() function in the same object work at the same time. Is this possible?
There are few problems:
the function ObjectA::run() blocks the event loop of the thread;
A.work() is called from the wrong thread;
it is needed to think about proper deletion of A.
Instead of blocking while loop in run() it is better to use timer. However, in that case the thread event loop should be executed (that it done in the default implementation of QThread::run(). So some other member slot should be used for that task to start, for example:
void ObjectA::doLoop()
{
emit query();
QTimer::singleShot(0, this, SLOT(doLoop()));
}
That function should be called when the thread is started, for example it can be done by connection in ObjectA constructor:
connect(this, SIGNAL(started()), this, SLOT(doLoop()));
Even better to keep private pointer QTimer* to be able to stop that timer from work() or to have some other control. Note that in that case QTimer object should be in the same thread as ObjectA.
Normally the ObjectA::work() function should be triggerd by some signal from handleQuery(). The event loop of ObjectA will catch that signal and the work() will be started in ObjectA thread.

ThreadPoolExecutor is not executing concurrently?

This is for my academic purpose only. Are the tasks that we add to the executor service are really executing in parallel. Well this is my example that raised this question
Runnable Class
public Tasks implement Runnable{
int taskCount;
public Tasks(int count){
this.taskCount = count;
}
public void run(){
System.out.println("In Task :"+taskcount +" run method");
}
}
Main Class
Class MyTest {
public static void main(String args[]){
ExecutorService service = Executors.newFixedThreadPool(10);
for(inti=0;i<10;i++){
Tasks taskObj = new Tasks(i);
service.submit(taskObj);
}
service.shutdown();
}
}
As soon as i submit a taskObj to the executor, the taskObj run() is invoked.
What if i have to something like this,
Add all the taskObj to the executor , the run() must not get invoked
Execute all the task objects at one shot. All the taskobj run() must be executed in parallel/concurrently
Please let me know
Thanks...V
If I understood you right, one way to solve this would be to use thread barriers. This might sound strange, but is actually implemented quite easy. You just take a variable (lets name it traffic-light) and make every thread loop on it. If you started enough threads (starting a new thread might consume some time) you just change it to green and all your threads will start execution at the same time.
For academic purposes we used to take an atomic-integer as counter (initialized with 0) and started n threads. The task of each threads was to increase the counter and then loop on it until it reached n. Like this you'll have all threads as parallel as possible.
If you still want to go with a thread pool system, you might have to implement your own thread system, where threads can wait upon a signal prior to grabbing work.
good luck

Fire off multiple synchronous threads

I'm not sure if this is a silly question as I don't know much about threads, but is it possible to fire off multiple synchronous threads at the same time, and wait for all to complete before acting? If it is how do you do it?
Certainly the simplest way is to use .NET 4.0 's Task Parallel Library (TPL).
e.g.
Parallel.For(0, 10, x =>
// Do this in Parallel.
System.Diagnostics.Debug.WriteLine(x)
);
see: http://msdn.microsoft.com/en-us/concurrency/bb964701
ut is it possible to fire off multiple synchronous threads at the same time, and wait for all to complete before acting?
"synchronous threads" is an oxymoron, they don't exist.
Of course you can start multiple threads and wait for them to complete (Thread.Join(otherThread))
If it is how do you do it?
Very rarely. Always use as few threads as possible. They are expensive.
Make sure you know about the ThreadPool and (Fx4) the Tasks library, TPL
You can use Parallel.Invoke.
This will execute the supplied actions in parallel and return when all are finished.
You can't really do anything at the same time, let alone fire threads :) (you can fire them rapidly one after the other though, although it is possible that a thread will start before the last one is fired).
As for waiting for them all before continuing, you can use the Join method, which waits for a thread to end before continuing.
Generally you'd do with the construct like below,
public class MultipleThreqadTest
{
private readonly Thread[] threads;
private readonly object locker;
private int finishCounter;
private readonly AutoResetEvent waitEvent;
public MultipleThreqadTest()
{
threads=new Thread[10];
for(int i=0;i<0;i++)
threads[i]=new Thread(DoWork);
finishCounter = threads.Length;
waitEvent=new AutoResetEvent(false);
}
public void StartAll()
{
foreach (var thread in threads)
{
thread.Start();
}
//now wait for all worker threads to complete
waitEvent.WaitOne();
}
private void DoWork()
{
//Do Some Actual work here, you may need to lock this in case you are workin on some shared resource
//lock(locker)
//{
//}
//Check if all worker thread complets
if(Interlocked.Decrement(ref finishCounter)==0)
{
this.waitEvent.Set();
}
}
}

Lock() not effective

I'm trying to lock an object whiel itterating through its elements. The arraylist allThreads of mine is really not locked, because during the execution of the "foreach" I get a exception saying "Collection was modified; enumeration operation may not execute." I thought that was the whole deal with lock?
lock (mApp.allThreads)
{
foreach (Thread t in mApp.allThreads)
if (t.Name == "OpcDAWriter" && t != Thread.CurrentThread)
t.Join();
}
I think you might have misunderstood what lock does for you. It does not prevent other code from manipulating the object that you have taken a lock on. What it does is to prevent one thread from acquiring a long on one object, while another thread is holding the lock.
If you want to prevent one thread from manipulating the collection while another thread is iterating over it, you will need to put both the iterating code, and the manipulating code within lock blocks, locking on the same object.
Simple sample:
class LockDemo
{
private IList<string> _items;
private object _lock = new object();
public LockDemo()
{
_items = new List<string>(new[] { "one", "two", "three" });
}
public void RemoveItem(string item)
{
lock (_lock)
{
_items.Remove(item);
}
}
public void DoSomethingThatIteratesOverTheList()
{
lock (_lock)
{
foreach (var item in _items)
{
// do something with item
}
}
}
}
Notice how all access to the list (except for the constructor in this case) are wrapped in lock blocks that are all locking on the same object. Also note that this object is not the list itself, but an object that is used only for locking purposes. This shows that lock does not lock the object as such, but provides a mechanism to control what parts of the code that may or may not be executed in parallel by different threads.
You are joining into the t thread, so it probably gets removed from mApp.allThreads or something else happens due to the join, thus modifying the collection.
Also, just because you are looking the object, not all other methods could lock on it, the lock only works when all methods accesing the object are locking on it. You could try using an external object as your lock parameter, ie:
private readonly _lock = new object();
[...]
lock(_lock)
{
foreach....
}
but I doubt that will change anything.

Resources