我不喜欢这段代码,但我总是对线程感到困惑,所以在我建议更改之前需要其他人的输入;这个线程安全吗(虽然是基于 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");
...
}
}
请您参考如下方法:
您不会回调任何其他线程。
您的代码将在新线程上执行委托(delegate),就像任何其他函数调用一样。
如果 getMessage 不是线程安全的,您的代码将会中断。
