简体   繁体   English

锁定和操作需要很长时间

[英]locking and operation taking long time

I think it's a common problem. 我认为这是一个普遍的问题。 For example, I have an array which is modified by one process/thread: 例如,我有一个由一个进程/线程修改的数组:

lock();
for(int i; i<array_size; i++) {
    // find an item and do some operations
}
unlock();

There is another process/thread which will print the whole array occasionally, but it may take a "long" time: 还有另一个进程/线程偶尔会打印整个数组,但可能要花很长时间:

lock()
for(int i; i<array_size; i++) {
    print(array[i]);
}
unlock();

Are there any better approaches to print the whole array? 有没有更好的方法来打印整个阵列?

如果是花费较长时间的打印部分,则可以锁定,获取阵列的副本,释放锁定并打印阵列副本。

What kind of locks do you use, mutex? 互斥锁,您使用哪种锁? Also what kind of consistency do you expect between the individual cells in your array, when (1) up update them, and (2) when you print them? 当(1)向上更新它们,以及(2)打印它们时,您还希望阵列中各个单元之间具有什么样的一致性? If each array-cell is independent, then why not just have many more locks each only responsible for that cells? 如果每个数组单元都是独立的,那么为什么不仅仅拥有更多的锁,每个锁仅负责该单元呢?

Like; 喜欢;

mutex locks[array_size];
for (int i=0; i< mutex_size; i++) {
   locks[i].lock();
    // do something or print content...
   locks[i].unlock();   
}

However if semantics of your array is such that the cells are not independent of each other but that you need atomic consistency across the array, then you are stuck with your original global lock. 但是,如果数组的语义使得各个单元不是彼此独立的,而是需要整个数组的原子一致性,那么您将陷入原始的全局锁中。

However you could still take a copy of the array under lock and then print the copy, as that would keep the lock of the array at a shorter time not having to wait for the print. 但是,您仍然可以在锁定状态下获取阵列的副本,然后打印副本,因为那样可以在较短的时间内保持阵列的锁定,而不必等待打印。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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