Can I make a thread-safe std::atomic>?

前端 未结 3 1482
醉话见心
醉话见心 2020-12-11 00:40

I\'m having a function that needs to be executed n=1000 times. This functions does a Monte Carlo style simulation and returns an int as the result.

3条回答
  •  情歌与酒
    2020-12-11 00:48

    You don't need to. It is totally okay to access a std::vector from multiple threads, if

    • you read objects
    • you write to different objects

    So just make sure, you create a vector of size n=1000 and depending on your thread number (1 to 4) you assign elements 0-249, 250-499 etc. to your threads.

    So each of your thread computes n/nthreads elements.

提交回复
热议问题