Sharing data between the main thread and concurrent tasks
You can share or exchange the data from the main thread with the tasks that have been spawned to run concurrently. V allows you to share data between the main thread and the tasks it spawns, but only using the variables that are of the struct
, map
, or array
type. These variables need to be specified using the shared
keyword in such cases. Variables marked using the shared
keyword need to be accessed using rlock
when they are being read or lock
when we want to read/write/modify those variables.
Let's consider a scenario where a fundraiser is raising money for a noble cause. A donor or multiple donors, if they wish to contribute to the fund, can contribute some amount to a fund manager (who represents the main function in our code). When the donations reach the target set by the fund, the fund manager stops collecting money. Assuming that this happens concurrently until the amount that's received is greater than or...