Multithreading in CLI/C++ performance issues

I got an application in CLI/C++ where i want to use Shared Memory for Signal Transfer.

When pressing the ConnectButton for the first time nothing happens.
Only after three or more tries the connection works, but the program lags a lot.

public: System::Void btnStartConnect_Click(System::Object^ sender, System::EventArgs^ e) {

    ConnectButtonPressed = true;

    msclr::interop::marshal_context context;
    shmNameA = context.marshal_as<const char*>(handleNameA);
    shmNameB = context.marshal_as<const char*>(handleNameB);

    // Start a new thread with the data transfer
    Thread^ transferSignalsThread = gcnew Thread(gcnew ThreadStart(TransferSignals));

    transferSignalsThread->Start();

}

public: System::Void btnStopConnect_Click(System::Object^ sender, System::EventArgs^ e) {

    TransferSignalsStop();

    
}

To clearify: The TransferSignal-Function uses Boost::Interprocess Library for Shared Memory Operation and sends the data from ProcessA to ProcessB. (in this example the numbers 0-100 in an infinite loop)
The TransferSignalsStop() just sets the ConnectButtonPressed flag to false.

In the past i just coded it with a while(true) loop and there it worked straight away and i got no lags. But the whole program froze, because the Connection Flag was not recognized anymore.

I would like to only have to press the Connect Button once and the program should not lag that much, when creating this parallel thread.

Additional question:
Is a mutex needed here, when just reading from a sharedmemory region where another process is only writing in?
Can my problem be solved in another way without having to use multithreading?

Leave a Comment