vendredi 19 juillet 2019

How do i do process syncronisation for the following code?

I have been trying to do some multithreading and process synchronisation. I am creating one parent and one child process using a fork. How do I implement the parent-child synchronisation?

I tried mutex, but ending in deadlocks.

// class1 threadfunction
void Class1::threadFunction()
{
    while(1)
    {
        std::cout<<"IN CLASS 1 FUNCTION\n\n";
        i++;
        sleep(2);
    }
}

//class 2 threadfunction
void Class2::threadFunction()
{
    while(1)
    {
        std::cout<<"IN CLASS 2 FUNCTION\n\n";
        j++;
        sleep(2);
    }
}

void Class1::create1()
{
    std::thread newThread (threadFunction);
    newThread.join();
}

void Class2::create2()
{
    std::thread newThread (threadFunction);
    newThread.join();
}

//main function

int main()
{
    std::cout<<"In Main\n\n";
    if(fork())
    {
        Class1 class1Object;
        class1Object.create1();
    }

    else
    {
        Class2 class2Object;
        class2Object.create2();
    }
}

I want the output to be sequential ex:

IN CLASS 1 FUNCTION
IN CLASS 2 FUNCTION
IN CLASS 1 FUNCTION
IN CLASS 2 FUNCTION
IN CLASS 1 FUNCTION
IN CLASS 2 FUNCTION
IN CLASS 1 FUNCTION
IN CLASS 2 FUNCTION

. . . .

Please suggest me how i could implement the same and what type of synchronisation i have to use

Aucun commentaire:

Enregistrer un commentaire