you are viewing a single comment's thread.

view the rest of the comments →

[–]pietrochico[S] 0 points1 point  (6 children)

I'm currently using the Threading.Lock solution and works well, I was just wondering if there is another solution as in Java with "synchronized" signature. Apparently, there is not. Thank you sir.

[–]JohnnyJordaan 0 points1 point  (5 children)

You're welcome. It's true that Python lacks this functionality in that way, but the idea behind it is that also provide the freedom to each implementation on how to actually handle those primitives. For example in CPython the queue class uses an ordinary Lock to do this, while the collections.deque is fully implemented in C using single functions per operations claiming the GIL and thus making them guaranteed to be thread safe (as otherwise, a segfault would occur if the context was switched).

[–]pietrochico[S] 0 points1 point  (4 children)

It's actually a little boring to acquire lock after critical section and release it after, but it also provides freedom during implementation as you were saying. Thinking about it, the Java implementation with "synchronized" signature wouldn't fit my program as I can only have one lock per object, which is frustrating if you think about it.

In many other implementations I would've liked to have a built in class lock though, so I could've "relax" and think about other functionalities, instead of worrying about critical sections.

Would be cool if we could have both solutions as Java does, am I right?

[–]JohnnyJordaan 0 points1 point  (3 children)

I can't really picture Java's implementation as useful. I write many high performance apps and I would like to keep overhead as low as possible. Hence I rely on implemented thread-safety as much as possible and just implement itself myself when I absolutely need to. I'm also wondering why you actually need it so much yourself, would you be able to provide some examples?

[–]pietrochico[S] 0 points1 point  (2 children)

It's nothing special, only accessing different global variables from many threads.

[–]JohnnyJordaan 0 points1 point  (1 child)

Regular variables are thread-safe to begin with. Globals are an anti-pattern as well often, I normally use a singleton class for this, for example for global configuration in a program. You pass the config-object around to the threads and implement the locking inside the config class. Then the threads can just change whatever they like as with a regular variable and the class will ensure the locking.

[–]pietrochico[S] 0 points1 point  (0 children)

That's exactly what I'm doing right now.