线程同步问题
我正在玩弄线程。我有一个问题,我认为这是一个非常基本的问题:
我有一个类:
Class Message {
public WriteMsg(string msg)
{
Console.Writeline(msg);
}
}
我创建这个类的一个对象
Message msg = new Message();
现在我创建十个线程并将这个消息对象传递给这十个线程执行的函数。每个线程都会将其线程索引传递给 writemsg ,该索引将被写出到 stdout 。我编写并测试了该应用程序及其写入线程索引 1 到 10。
如您所见,我没有实现任何类型的同步。如果该类仅执行上述功能,那么在访问线程中的对象时是否需要锁定机制?
I am playing around with threads. I have a question and I think its a very basic one:
I have a class:
Class Message {
public WriteMsg(string msg)
{
Console.Writeline(msg);
}
}
I create an object of this class
Message msg = new Message();
Now I create ten threads and pass this message object to the function executed by the ten threads. Each will pass its thread index to the writemsg , which will be written out to stdout. I wrote and tested the application and its writing thread index 1 through 10.
As you can see I have not implemented no kind of synchronization. If the class is doing just the functionality mentioned above, do I need a lock mechanism when accessing the object in the threads ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果线程正在使用共享变量,则需要在线程之间进行同步。
在您的简单示例中没有共享变量。所以不需要同步
You need synchronization among threads if they are working working with shared variables.
In your simple example there is no shared variable. So no synch is needed
如果是修改或读取非原子对象的方法,这取决于您正在做什么。对于你的情况没有必要。
It depends on what you're doing if it's methods that modify or read from non-atomic objects than yes. For your case it's not necessary.