How to make something lwt supported?

I am trying to understand the term lwt supported .


So, suppose I have a piece of code that connects a database and writes some data: Db.write conn data . This is not related to lwt yet, and each entry will cost 10 sec .

Now I would like to use lwt. Can I directly code as shown below?

 let write_all data_list = Lwt_list.iter (Db.write conn) data_list let _ = Lwt_main.run(write_all my_data_list) 

Are data items 5 my_data_list in my_data_list , will all five data items be written to the database sequentially or in parallel?


Also in Lwt manually or http://ocsigen.org/tutorial/application they say

Using Lwt is very simple and does not cause problems if you never use locking functions (incompatible functions). Blocking functions may cause entre! Server to freeze

I absolutely do not understand how not to use blocking functions. For each of my own functions, can I just use Lwt.return to make it lwt support ?

+4
source share
1 answer

Yes, your code is correct. The principle of lwt supported is that anything that could potentially take time in your code should return an Lwt value.

About Lwt_list.iter, you can choose whether you want the treatment to be parallel or sequential by choosing between iter_p and iter_s :

In iter_s fl, iter_s will call f for each element of l, waiting for completion between each element. In contrast, in iter_p fl, iter_p will call f on all elements of l, and then wait for all threads to complete.

On non-blocking functions, the principle of luminous flux is that they continue to work until they reach the "point of cooperation", i.e. points where the thread can be safely interrupted or has nothing to do, as in sleep .

But you need to declare that you enter a “collaboration point” before doing sleep . That's why the whole Unix library was wrapped, so when you want to perform a time-consuming operation (like a write ), a collaboration point is automatically reached.

For your own function, if you use I / O from Unix, you should use the Lwt version instead ( Lwt_unix.sleep instead of Unix.sleep )

+4
source

Source: https://habr.com/ru/post/1489252/


All Articles