Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/visual-studio-code/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C 向量上的并发性,其中每个单元在32位体系结构上为8位_C_Multithreading_Concurrency_Architecture - Fatal编程技术网

C 向量上的并发性,其中每个单元在32位体系结构上为8位

C 向量上的并发性,其中每个单元在32位体系结构上为8位,c,multithreading,concurrency,architecture,C,Multithreading,Concurrency,Architecture,让我们假设有一个向量的并发情况。 每个线程以写和读模式访问数组的不同单元 我将展示一段“类似C/C++的”代码片段,只是想给大家一个想法: uint8_t vector[SIZE]; void thread(int id_thread) { // vector is a global variable, same for all threads vector[id_thread] = id_thread; } // Somewhere for (i = 0; i < SIZE;

让我们假设有一个向量的并发情况。 每个线程以写和读模式访问数组的不同单元

我将展示一段“类似C/C++的”代码片段,只是想给大家一个想法:

uint8_t vector[SIZE];

void thread(int id_thread) {
  // vector is a global variable, same for all threads
  vector[id_thread] = id_thread;
}

// Somewhere
for (i = 0; i < SIZE; ++i) {
  createThread(thread, i);  // create a thread and passing i as id_thread
}
我错了吗?处理器可以在内存中写入单个字节,而无需以任何方式(包括缓存)相邻字节


谢谢。

编译器可以自由地将写操作实现为机器指令,但只要它不能破坏单线程代码,它就可以实现。例如,它可以将32位值读入寄存器,更改相应的字节,然后将32位值写回内存。这将破坏其他写入。

只需确保根据系统对齐方式在线程之间分割工作即可。每个线程都应该有
n*对齐
字节的数据来处理。我相信有某种机制,就像Scott Meyers所说的“将其标记为脏”,并禁止两个线程在打算写入缓存线时同时使用同一缓存线(仅读取缓存线时不会发生)。顺便说一句,“32位体系结构”并不真正指定CPU是否能够以原子方式寻址和读/写单个字节的内存。这是CPU的另一个属性。
[0] [0] [0] [0] ... [0]
_______________   
  uint8 * 4

thread1:   [1] [0] [0] [0]  and write in memory 
thread2:   [0] [1] [0] [0]  and write in memory
           ---------------
           overlap if processor write 32-bit at least.