Simultaneous execution of two functions

I want to run two functions one after another, which access the third function with the condition that when the first uses the third, the second function must wait. He should be able to use the third function after the first period of access to the third function.

This concept sounds like an implementation of cyclic planning with context switching. I know this theoretically, but I want to apply it practically. How can I achieve this and switch to context? Can someone provide me an example for this? Is there any other way to achieve this?

EDIT: Actually, I draw markers on Google maps using gmap.net.i created two stream functions for two markers. They will extract the required data from two separate files. Converting it to long long and plotting a map.with this approach I create duplicate functions for both functions with the same functionality. But I think this is not a very good way of programming, so you want to use one common function to build and extract data from a file for conversion.

therefore, when one thread accesses a common function, the other must wait. First, release the function or its time period to work on this function, it must perform a context switch, and the second thread must access the general function. this is what i am trying to achieve. If I have to change my approach, please let me know. enter image description here

+5
source share
1 answer

It appears that 2 lock tasks should do what you want:

class Program { static void Main(string[] args) { var task1 = Task.Run(() => Func1()); var task2 = Task.Run(() => Func2()); Task.WaitAll(task1, task2); } static object lockObj = new object(); static void Func1() { for (int i = 0; i < 10; i++) { Func3("Func1"); Thread.Sleep(1); } } static void Func2() { for (int i = 0; i < 10; i++) { Func3("Func2"); Thread.Sleep(1); } } static void Func3(string fromFn) { lock(lockObj) { Console.WriteLine("Called from " + fromFn); } } } 

Blocking prevents the execution of closed code in more than one thread. ( Sleep statements exist only to slow down functions for demo purposes - they will not occur in your final code).

Output:

 Called from Func2 Called from Func1 Called from Func2 Called from Func1 Called from Func2 Called from Func1 Called from Func1 Called from Func2 Called from Func1 Called from Func2 
+8
source

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


All Articles