开发者

Static Methods and Multi-Threading

Can there be any problems in having a static class with only static开发者_如何学Python methods (no properties, fields or anything else) and having several threads accessing those methods at the same time?


As long as there is no shared state or external resources, then: no risk whatsoever. You've mentioned "no fields" etc, which is good - so as long as they aren't indirectly talking shared state (perhaps via some common argument that isn't thread-safe in this scenario, or via some other utility methods that it calls, which share state in messy ways), you should be fine.


Yes, there can. It depends how your methods are written. Now, if there are only static methods, this would theoreitcally mean fully reentrant code without problems.


Potentially, yes.

Imagine:

class Logger
{
    WriteToLogs(string msg)
    {
        // Write data to file1
        ... 

        // Write data to file2
        ...
    }
}

Now imagine you have multiple threads trying to call WriteToLog() simultaneously. What happens when thread2 gets scheduled before thread1 is done writing to the log files? You could end up with all manner of data corruption in this case.

Static classes and methods do NOT inherently provide any form of thread synchronization, locking, etc. That's for YOU to design and implement.


Yes, for instance singleton implementations can be static but they have to implement mechanisms such as double checked locking to prevent multithreading issues.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜