How to create a vector of mutexes

Discussion about recent product features & solutions!
Search

Post Reply
2 posts • Page 1 of 1
smagnoni
Posts: 2
Joined: Tue Nov 21, 2017 2:26 pm

How to create a vector of mutexes

Post by smagnoni »

Hello, I have multiple devices to which I communicate via TCP socket.
As I have multiple threads which can potentially write at the same time I need a mutex to prevent writes to collide.
I have seen that WinCC-OA has a “synchronized” function which is basically a mutex. I have tested this, and it works with no problem as long as I use this on a standard variable like int or bool.
As I have multiple devices and one socket per device I would rather have one mutex per device and this seams not too work as passing a mapping or a vector gives syntax error.

I have recreated the problem in a small example here:

Code: Select all

mapping mutexes;   // map containing one mutex per device
bool commonMutex;  // mutex shared across all devices

void foo(string deviceName)
{
    while(true)
    {
        synchronized(mutexes[deviceName]) // Why this cannot be done???
        //synchronized(commonMutex)           // this works but it is too constraining
        {
            DebugN("foo critical part");
        }
        delay(0,1);
    }
}


void bar(string deviceName)
{
    while(true)
    {
        synchronized(mutexes[deviceName]) // Why this cannot be done???
        //synchronized(commonMutex)      // this works but it is too constraining
        {
            DebugN("bar critical part");
        }
        delay(0,1);
    }
}


void main()
{ 
    dyn_string deviceList = makeDynString("device1","device2","device3");

    for (int i = 1; i

User avatar
mkoller
Posts: 741
Joined: Fri Sep 17, 2010 9:03 am

Re: How to create a vector of mutexes

Post by mkoller »

Use sempahores instead. Check CTRL docs for semAcquire(), semRelease(), etc.
Semaphores have a string as identifier, so you can easily create a semaphore per device

Post Reply
2 posts • Page 1 of 1