Thread safe array for std :: thread?

mystruct** = (mystruct**)calloc(10, sizeof(mystruct*);
for(unsignd int i = 0; i < 10; i++)
    mystruct[i] = (mystruct*)calloc(10, sizeof(mystruct);

thread t[10];

for(unsigned int i = 0; i < 10; i++)
    t[i] = thread(new_piece, mystruct[i]);

for(unsigned int i = 0; i < 10; i++)
    t[i].join();

The function new_piecewrites data to mystruct[i]. To be more specific, the function changes the values.mystruct[i][0], mystruct[i][1], ..., mystruct[9]

How to make a safe workflow higher?

+4
source share
1 answer

As mentioned in the comments, the code seems to be "thread safe", however it may suffer from "cache hijacking".

First let me explain what it is and why it can happen in your code:

What is caching:

"-" - , . : . , . - 64 .

, , , , , . , , .

(. wiki ), , )

(. : Dr.Dobb article )

:

, calloc malloc, . (. man 3 calloc, FreeBSD).

++ new .

, , calloc malloc, , , mystruct, -.

"":

, (. wiki ).

, (mystruct), :

  • malloc calloc -.

  • posix: posix_memalign, <stdlib.h> (. opengroup posix_memalign)

  • ++ 11 std::aligned_storage (. )

    std::aligned_storage type, , .

    , - , N :

    struct mystruct { ... };
    
    const std::size_t cache_line_size = 64;
    
    typename std::aligned_storage<sizeof(mystruct), cache_line_size>::type storage[N];
    

    , N- mystruct s, mystruct . IMO, , calloc mystruct.

    . , - - .

+6

Source: https://habr.com/ru/post/1526446/


All Articles