开发者

Thread synchronization question

开发者 https://www.devze.com 2023-02-19 13:05 出处:网络
I am playing开发者_C百科 around with threads. I have a question and I think its a very basic one:

I am playing开发者_C百科 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 ?


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消