线程同步问题

发布于 2024-10-26 22:12:41 字数 413 浏览 2 评论 0原文

我正在玩弄线程。我有一个问题,我认为这是一个非常基本的问题:

我有一个类:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

谁与争疯 2024-11-02 22:12:41

如果线程正在使用共享变量,则需要在线程之间进行同步。
在您的简单示例中没有共享变量。所以不需要同步

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

旧时模样 2024-11-02 22:12:41

如果是修改或读取非原子对象的方法,这取决于您正在做什么。对于你的情况没有必要。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文