I have a function that accepts an integer pointer as an argument, which it then alters. I have several instances of the function running on separate threads - some that have the same integer as the argument.
我有一个接受整数指针作为参数的函数,然后它会改变。我有几个函数在不同的线程上运行 - 有些与参数具有相同的整数。
I need to pause the instance of the function if the argument is being altered by another instance of the function on another thread and resume when the other instance has completed altering the variable.
如果参数被另一个线程上的另一个函数实例更改,我需要暂停函数的实例,并在另一个实例完成更改变量时恢复。
The seemingly obvious solution that to this kind of problem would be an NSLock or a POSIX mutex, however this would prevent all instances of the function from continuing, even if the integer argument is different.
对于这种问题看似明显的解决方案是NSLock或POSIX互斥锁,但是这会阻止函数的所有实例继续,即使整数参数不同。
For a more intuitive idea of what I mean consider the following:
为了更直观地了解我的意思,请考虑以下事项:
void theFunction (int *argument)
{
NSLock *theLock = [NSLock new];
[theLock lock];
(*argument) ++;
[theLock unlock];
}
The above code would prevent all instances of the function from running, however I only need to pause the instances of the function where the integer argument is the same. How can I lock the variable specifically, as to pause any instances attempting to read or write to it until it is unlocked?
上面的代码会阻止函数的所有实例运行,但是我只需要暂停整数参数相同的函数实例。如何专门锁定变量,以便在解锁之前暂停任何尝试读取或写入的实例?
2 个解决方案
#1
1
If you have the int*, consider using the atomic increment operation (see man on OSAtomicAdd32). It's pretty cheap to per-value locking that you want.
如果您有int *,请考虑使用原子增量操作(请参阅OSAtomicAdd32上的man)。对于你想要的每值锁定来说,这是非常便宜的。
#2
0
Use a separate lock for each argument?
为每个参数使用单独的锁?
#1
1
If you have the int*, consider using the atomic increment operation (see man on OSAtomicAdd32). It's pretty cheap to per-value locking that you want.
如果您有int *,请考虑使用原子增量操作(请参阅OSAtomicAdd32上的man)。对于你想要的每值锁定来说,这是非常便宜的。
#2
0
Use a separate lock for each argument?
为每个参数使用单独的锁?