In .NET multithreading we have to assign a thread to a method of a
separate object each time (and not two methods of the same object)?
In other words, why does this hung?
#using <mscorlib.dll >
using namespace System;
using namespace System::Threadi ng;
class SomeException
{};
__gc class SomeClass
{
int index;
//...
public:
// ...
void DoSomething()
{
Monitor::Enter( this);
throw SomeException() ;
// Modify index
Monitor::Exit(t his);
}
void DoSomethingElse ()
{
Monitor::Enter( this);
// Modify index
Monitor::Exit(t his);
}
// ...
};
int main() try
{
SomeClass *ps= __gc new SomeClass;
Thread *pthread1= __gc new Thread ( __gc new ThreadStart(ps,
&SomeClass::DoS omething) );
Thread *pthread2= __gc new Thread ( __gc new ThreadStart(ps,
&SomeClass::DoS omethingElse) );
//Start execution of ps->DoSomething( )
pthread1->Start();
//Start execution of ps->DoSomethingEls e()
pthread2->Start();
}
catch(SomeExcep tion)
{
Console::WriteL ine("SomeExcept ion caught in main thread!\n");
} 10 1300
Ioannis Vranos wrote: In .NET multithreading we have to assign a thread to a method of a separate object each time (and not two methods of the same object)?
In other words, why does this hang?
I had pasted wrong code. Here is the correct one:
#using <mscorlib.dll >
using namespace System;
using namespace System::Threadi ng;
class SomeException
{};
__gc class SomeClass
{
int index;
//...
public:
// ...
void DoSomething() try
{
Monitor::Enter( this);
throw SomeException() ;
// Modify index
Monitor::Exit(t his);
}
==> Handle inside the specific thread locally
catch(SomeExcep tion)
{
// ...
}
void DoSomethingElse ()
{
Monitor::Enter( this);
// Modify index
Monitor::Exit(t his);
}
// ...
};
int main() try
{
SomeClass *ps= __gc new SomeClass;
Thread *pthread1= __gc new Thread ( __gc new ThreadStart(ps,
&SomeClass::DoS omething) );
Thread *pthread2= __gc new Thread ( __gc new ThreadStart(ps,
&SomeClass::DoS omethingElse) );
//Start execution of ps->DoSomething( )
pthread1->Start();
//Start execution of ps->DoSomethingEls e()
pthread2->Start();
}
catch(Exception *pe)
{
Console::WriteL ine("{0}", pe->Message);
}
On Fri, 25 Mar 2005 06:00:34 +0200, Ioannis Vranos wrote: Ioannis Vranos wrote:
In .NET multithreading we have to assign a thread to a method of a separate object each time (and not two methods of the same object)?
In other words, why does this hang?
I had pasted wrong code. Here is the correct one:
#using <mscorlib.dll >
using namespace System; using namespace System::Threadi ng;
class SomeException {};
__gc class SomeClass { int index;
//...
public:
// ...
void DoSomething() try { Monitor::Enter( this);
throw SomeException() ;
// Modify index
Monitor::Exit(t his); }
==> Handle inside the specific thread locally catch(SomeExcep tion) { // ... }
void DoSomethingElse () { Monitor::Enter( this);
// Modify index
Monitor::Exit(t his); }
// ... };
int main() try { SomeClass *ps= __gc new SomeClass;
Thread *pthread1= __gc new Thread ( __gc new ThreadStart(ps, &SomeClass::DoS omething) );
Thread *pthread2= __gc new Thread ( __gc new ThreadStart(ps, &SomeClass::DoS omethingElse) );
//Start execution of ps->DoSomething( ) pthread1->Start();
//Start execution of ps->DoSomethingEls e() pthread2->Start(); }
catch(Exception *pe) { Console::WriteL ine("{0}", pe->Message); }
I can't get this to hang.
You're starting two threads to run functions on the object ps, which is
fine in and of itself. However, the function DoSomething locks ps, throws
an exception, and apparently fails to unlock ps. Provided the thread goes
on to exit, I believe this will abandon the sync object associated with ps,
making it available to DoSomethingElse . If for some reason DoSomething
doesn't exit, then there's the potential for DoSomethingElse to wait
forever, and your program will hang. The solution to that is to unlock
"this" inside your catch block. (Of course, this all assumes the threads
execute in the order they're created.)
--
Doug Harrison
Microsoft MVP - Visual C++
Doug Harrison [MVP] wrote: I can't get this to hang.
Strangely enough, it does not hang always. Run it sometimes and you will
see it hanging. I can not understand why it does not hang all the time
though (since Monitor::Exit() is not called in the catch block).
You're starting two threads to run functions on the object ps, which is fine in and of itself. However, the function DoSomething locks ps, throws an exception, and apparently fails to unlock ps. Provided the thread goes on to exit, I believe this will abandon the sync object associated with ps, making it available to DoSomethingElse . If for some reason DoSomething doesn't exit, then there's the potential for DoSomethingElse to wait forever, and your program will hang. The solution to that is to unlock "this" inside your catch block. (Of course, this all assumes the threads execute in the order they're created.)
Yes, Monitor::Exit(t his); inside the catch block makes the program to
never hang. However why it hangs sometimes and sometimes it doesn't,
without this?
On Fri, 25 Mar 2005 08:20:05 +0200, Ioannis Vranos wrote: Strangely enough, it does not hang always. Run it sometimes and you will see it hanging. I can not understand why it does not hang all the time though (since Monitor::Exit() is not called in the catch block).
FWIW. I ran it 20 times in a row, and it never hung. Aren't MT problems
fun?
Yes, Monitor::Exit(t his); inside the catch block makes the program to never hang. However why it hangs sometimes and sometimes it doesn't, without this?
It turns out I was wrong. Unlike a mutex, the SyncBlock associated with an
object is not abandoned when a thread exits while holding it. However, I
was on the right track when I alluded to order issues. Provided thread 1
runs before thread 2, locks the object, and exits, thread 2 will block
forever on its Monitor.Enter call. To make it do so (almost)
deterministical ly, insert the following at the start of DoSomethingElse :
Thread::Sleep(1 000);
This should give thread 1 enough time to do its thing and mess up thread 2.
--
Doug Harrison
Microsoft MVP - Visual C++
Doug Harrison [MVP] wrote: Strangely enough, it does not hang always. Run it sometimes and you will see it hanging. I can not understand why it does not hang all the time though (since Monitor::Exit() is not called in the catch block).
FWIW. I ran it 20 times in a row, and it never hung. Aren't MT problems fun?
I compiled it from command line, with cl /clr /EHsc temp.cpp and no
other switch. /EHsc is important. Yes, Monitor::Exit(t his); inside the catch block makes the program to never hang. However why it hangs sometimes and sometimes it doesn't, without this?
It turns out I was wrong. Unlike a mutex, the SyncBlock associated with an object is not abandoned when a thread exits while holding it. However, I was on the right track when I alluded to order issues. Provided thread 1 runs before thread 2, locks the object, and exits, thread 2 will block forever on its Monitor.Enter call. To make it do so (almost) deterministical ly, insert the following at the start of DoSomethingElse :
Thread::Sleep(1 000);
This should give thread 1 enough time to do its thing and mess up thread 2.
Does it hang to you with this way? :-)
Hi Ioannis, void DoSomething() { Monitor::Enter( this);
throw SomeException() ;
// Modify index
Monitor::Exit(t his); }
The abouve code will always forget to call the "Exit" !
Normally you should *always* do:
Monitor::Enter( this);
__try
{
}
__finally
{
Monitor::Exit(t his);
}
--
Greetings
Jochen
My blog about Win32 and .NET http://blog.kalmbachnet.de/
On Fri, 25 Mar 2005 10:49:31 +0200, Ioannis Vranos wrote: Doug Harrison [MVP] wrote: To make it do so (almost) deterministical ly, insert the following at the start of DoSomethingElse :
Thread::Sleep(1 000);
This should give thread 1 enough time to do its thing and mess up thread 2.
Does it hang to you with this way? :-)
Yes. I said "almost" deterministical ly because it's using Sleep to fake out
the scheduler, a practice that isn't guaranteed to work but does well
enough to demonstrate the problem.
Aside: It's interesting to note that by using the Thread class, your
example illustrated the use of foreground threads. Had you used background
threads, or if you were to set the IsBackground property on the threads,
your program would have terminated right away, because extant background
threads don't keep a program alive once the primary thread has exited. Only
foreground threads do that. In general, you should join with your secondary
threads before exiting your primary thread.
--
Doug Harrison
Microsoft MVP - Visual C++
Doug Harrison [MVP] wrote: Yes. I said "almost" deterministical ly because it's using Sleep to fake out the scheduler, a practice that isn't guaranteed to work but does well enough to demonstrate the problem.
Aside: It's interesting to note that by using the Thread class, your example illustrated the use of foreground threads. Had you used background threads, or if you were to set the IsBackground property on the threads,
.... the only way that I know for creating .NET background threads. Is
there another?
your program would have terminated right away, because extant background threads don't keep a program alive once the primary thread has exited.
Yes indeed.
Only foreground threads do that. In general, you should join with your secondary threads before exiting your primary thread.
You mean to join the primary thread and secondary threads all together?
However this doesn't sound much multithreading. :-)
Something else based on this, is it better to join dependent threads -
whenever possible- instead of using locks? What would this mean for
performance in multi-cpu/core environments? Is this a way to avoid the
thread lock mess, while sacrificing almost no speed?
On Sat, 26 Mar 2005 04:34:26 +0200, Ioannis Vranos wrote: ... the only way that I know for creating .NET background threads. Is there another?
Thread pool and by extension asynchronous delegates. In addition, unmanaged
threads that call into managed code are marked as background threads.
You mean to join the primary thread and secondary threads all together? However this doesn't sound much multithreading. :-)
But if your program is shutting down, it's usually undesirable to allow
your secondary threads to continue to run as the larger environment in
which they're executiing is going away. To conduct an orderly shutdown,
your primary thread has to ask all your secondary threads to exit and join
with them first.
Something else based on this, is it better to join dependent threads - whenever possible- instead of using locks?
Not sure what you mean. By "join" I mean wait for the thread to exit.
What would this mean for performance in multi-cpu/core environments? Is this a way to avoid the thread lock mess, while sacrificing almost no speed?
Google on "lock-free programming". It's a hot topic these days.
--
Doug Harrison
Microsoft MVP - Visual C++ This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
by: John Brock |
last post by:
I have a base class with several derived classes (I'm writing in
VB.NET). I want each derived class to have a unique class ID (a
String), and I want the derived classes to inherit from the base
class *Shared* methods which make use of the class ID.
So I gave the base class a classID field, and then I gave the
derived classes Shared constructors, which I used to set the classID
field to the appropriate values for each derived class. But...
|
by: VM |
last post by:
I'm trying to add multithreading to my win application but I'm having
trouble with the code since the method to be threaded has parameters. How
can I add multithreading to a method with parameters? MSDN says ThreadStart
cannot take parameters, so how can I do it?
public System.Threading.Thread Thread_LoadAZM;
public void LoadFile(string sFileName)
{
Thread_LoadAZM=System.Threading.Thread(new...
|
by: Bill Thorne |
last post by:
We have a COM object that has been wrappered for use in .NET and which can
make calls which can take a while to execute. These are mainframe
integration calls that might perform a lot of data entry and gathering,
returning the results to the ASP.NET caller.
I have tried an AsyncPage class (implements IHttpAsyncHandler and uses
custom thread pool class from DevelopMentor.ThreadPool
-http://staff.develop.com/woodring); I have tried the...
|
by: sk |
last post by:
Hi,
I'm trying to override the Render method of my Page class. Are there any
standard guidelines for this?
Thanks.
Shardul
|
by: Giovanni Bassi |
last post by:
Hello Group,
I am running an operation in a different thread. There are resources that
are released when the thread is done running. This is done at the end of the
execution as it raises an event, and then the operation handling this event
calls threaded object's dispose method.
The problem is: If an exception is thrown the event is never raised, the
operation never executes dispose and my resources get stuck on the memory
until the app...
| |
by: S Shulman |
last post by:
Hi
I am looking for a method that allows calling a method that will be executed
by the main application thread bu will be called from any thread that I
create manually.
(I think that technically it is similar to sending a message to the
program)
I tried the Invoke method but it seem to work from the calling thread
|
by: Brian Parker |
last post by:
I inherited a C++ DLL that I need to remotely call multiple times
asynchronously. What I have developed is:
CSharp web application that makes asynchronous calls to a CSharp Web
Service. The Web Service calls the DLL, which does some heavy
processing, then sends the results back to the CSharp web application.
The problem is that the calls to the DLL in the Web Service are blocking
each other. If I send 10 async requests to the Web...
|
by: Ray |
last post by:
Hello,
Greetings! I'm looking for a solid C++ multithreading book. Can you
recommend one? I don't think I've seen a multithreading C++ book that
everybody thinks is good (like Effective C++ or Exceptional C++, for
example). Platform-specific (e.g.: Win32, POSIX) is OK, as long as it's
good :)
Thank you,
Ray
|
by: PokerMan |
last post by:
Hi
I have a situation where a method is fired from receiving a message from my
server.
On receiving this message it triggers a visual animation.
So what happens when the server sends say 3 messages in quick succession.
I want the method to fire, animate completely, and then fire again, finish
|
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...
|
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...
| |
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...
|
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...
|
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();...
|
by: adsilva |
last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
|
by: 6302768590 |
last post by:
Hai team
i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
|
by: muto222 |
last post by:
How can i add a mobile payment intergratation into php mysql website.
| |
by: bsmnconsultancy |
last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...
| |