开发者

C++ g++ thread-safety constructors

开发者 https://www.devze.com 2022-12-20 18:51 出处:网络
Given: class Foo { Foo() {}; }; class Bar { static int counter; Bar() { ++counter; } } It\'s clear that Foo::F开发者_运维技巧oo is thread safe whereas Bar::bar is not.

Given:

class Foo {
  Foo() {};
};

class Bar {
  static int counter;
  Bar() { ++counter; }
}

It's clear that Foo::F开发者_运维技巧oo is thread safe whereas Bar::bar is not.

Furthermore, it's clear that if a function is written in such a way so that it's not thread-safe, then clearly putting it in a constructor makes that constructor not thread safe.

However, are there extra gotchas that I need to worry about constructors? I.e. a piece of code with mutex/locks such that if it was in a function body, it would be thread safe, but if I stuck it in a constructor, based on the complexity of C++'s constructors, weird things happen and it's no longer thread safe?

Thanks!

Edit: you can assume I'm using g++.


I would avoid any static values in an object used by a thread.

Why not pass in the value needed as a parameter for the constructor?

Or actually, put a mutex around the constructor in your thread. I wouldn't let the other classes be responsible for that.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号