I don’t like this code but I always get confused with threads so wanted someone else’s input before I suggest a change; Is this thread safe (Psuedo code though based on C#):
class ThreadCreator
{
private AnObject obj = new AnObject();
public ThreadCreator()
{
for (int i = 0; i < 100; ++i)
{
ThingToThread th = new ThingToThread();//don't care about losing ref to th for this question
th.sendMsg = this.getMessage;
Thread t = new Thread(th.doThing);
t.SetApartmentState(ApartmentState.STA);
t.Start();
}
}
public void getMessage( string stuff )
{
...
obj.DoThing(stuff);
...
}
}
class ThingToThread
{
public delegate void sendMsg(string stuff);
public void doThing()
{
...
this.sendMsg("ohh that's interesting");
...
}
}
You aren’t calling back to the any other thread.
Your code will execute the delegate on the new thread, just like any other function call.
If
getMessageis not thread-safe, your code will break.