作者:小哥 | 来源:互联网 | 2023-09-14 08:02
I have a struct with some integers field, like
我有一个有一些整数场的结构,比如。
struct s {
int a;
int b;
int c;
int max;
};
struct s mystruct = {0, 0, 0, 0}; // Global var
And then I have N threads that sometimes have to do things like ++
or --
on the first three fields, and sometimes have to read them and then update the max
field. Do I have to use a mutex here? And if yes, is it needed only when reading/updating max
or always? Why? If I just increment or decrement the first three fields, does it matter if a thread runs before another?
然后我有N个线程它们有时需要做一些事情比如++或-在前三个字段上,有时需要读取它们然后更新max字段。我必须在这里使用互斥锁吗?如果是,它是否只需要在读取/更新max或always时?为什么?如果我只是增加或减少前三个字段,那么一个线程在另一个线程之前运行是否有关系?
3 个解决方案