Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I ignore thread safety when programming in Erlang?

I've just started learning about thread safety. This is making me code a lot more defensively, perhaps too defensively.

Would using a functional language like Erlang completely rid me of this concern?

like image 518
Aillyn Avatar asked Aug 19 '10 16:08

Aillyn


People also ask

Why do we need thread safety?

Thread Safety in Java is a very important topic. Java provides multi-threaded environment support using Java Threads, we know that multiple threads created from same Object share object variables and this can lead to data inconsistency when the threads are used to read and update the shared data.

What does thread-safe mean in programming?

Thread safety is the avoidance of data races—situations in which data are set to either correct or incorrect values, depending upon the order in which multiple threads access and modify the data. When no sharing is intended, give each thread a private copy of the data.

Is Erlang multithreaded?

Nginx and Erlang most certainly use multiple threads by default. They both use thread pools.

Are pure functions thread-safe?

Pure functions are easier to parallelize “If there is no data dependency between two pure expressions, then their order can be reversed, or they can be performed in parallel and they cannot interfere with one another (in other terms, the evaluation of any pure expression is thread-safe).”


2 Answers

in Erlang the unit of execution state isn't a thread, but a process. yeah, it's a lightweight kind of process implemented on top of threads; but it's more like a process than a thread.

The main point is that processes don't share state, they pass messages; while threads share everything by default, and have to arbitrate to avoid chaos.

thus, you don't need thread safety since you're not working with threads.

like image 121
Javier Avatar answered Sep 30 '22 04:09

Javier


Javier is right.

However, I'd like to just add something as it has caught me before. If you are working with a built-in driver or nif it may not be thread safe anymore. It seems obvious since the driver or nif will be using C or C++ code, but it's worth mentioning. So you can't completely ignore thread safety just because you are using Erlang.

like image 36
Kyle d'Oliveira Avatar answered Sep 30 '22 03:09

Kyle d'Oliveira