简体   繁体   中英

Running two functions concurrently

I want to run two functions one after the other that accesses a third function with a condition that when the first is using the third, the second function should wait. It should be able to use the third function after first time period of accessing the third function over.

This concept sounds like implementing round robin scheduling with context switching. I know this theoretically, but I want to apply it practically. How can I achieve this and do context switching? Can someone provide me an example to do this? Is there any other way to achieve this as well?

EDIT: Actually i am plotting markers on google maps ,using gmap.net .i have created two thread functions for the two markers.they will be fetching the required data from two separate files.converting it into lat long and plotting on map.with this approach i am creating duplicate functions for both having same functionality.but i guess its not a good way of programming so want to use one common function for plotting and fetching data from file to convert .

so when one thread is accessing the common function another one should wait .once first one release the function or its time period to work on that function is exceeded it should perform context switch and second thread should access the common function. this is what i am trying to achieve.if i should modify my approach please do let me know. 在此输入图像描述

Sounds like 2 tasks with a lock 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);
        }
    }
}

The lock prevents the enclosed code from running in more than one thread at once. (The Sleep statements are there purely to slow the functions down for demonstration purposes - they will have no place in your final code).

Output is:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM