How does static code run with multiple threads?

后端 未结 6 889
青春惊慌失措
青春惊慌失措 2021-01-04 06:38

I was reading Threading from within a class with static and non-static methods and I am in a similar situation.

I have a static method that pulls data from a resourc

6条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-04 07:19

    The static method will run on the thread that you call it from. As long as your function is re-entrant, meaning execution can safely re-enter the function while execution from another thread (or further up the stack) is already in the function.

    Since your function is static, you can't access member variables, which would be one way of making it not re-entrant. If you had a static local variable that maintained state, that would be another way of making it not re-entrant.

    Each time you enter you create a new MyObject, so each bit of execution flow is dealing with it's own MyObject instance, which is good. It means they won't be trying to access the same object at the same time (which would lead to race-conditions).

    The only thing you're sharing between multiple calls is the Console itself. If you call it on multiple threads, they'll output over each other to the console. And you could potentially act on the same file (in your example the filename is hard-coded), but you'd probably be acting on multiple files. Successive threads would probably fail to open the file if previous ones have it open.

提交回复
热议问题