c++ - 在不同线程中作为一个类的成员函数使用安全吗?

标签 c++ multithreading boost glib

例如:

struct A {    
void run1() {}
void run2() {}    
};

int main()
{
  A a;

  thread t1(bind(&A::run1, ref(a)));
  thread t2(bind(&A::run2, ref(a)));

  // not joinable thread!

  int i;
  std::cin >> i;
}

请看这个例子http://developer.gnome.org/glibmm/unstable/thread_2thread_8cc-example.html

a 对象是否应该由互斥锁或其他东西保护?这里没有竞争条件吗?

最佳答案

这取决于方法中的代码。如果方法中没有比赛,那很好。您的示例中没有,因为没有代码;)

在您的示例中,“a”可能会在线程退出之前被销毁(如果用户速度很快)。

关于c++ - 在不同线程中作为一个类的成员函数使用安全吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9241222/

相关文章:

c++ - 如何将从文件中读取的一行拆分为多个整数?

C++:比较 boost::filesystem 中的路径时如何忽略第一个目录路径?

c++ - 从文件中读入时如何阻止空格显示为回车?

c++ - 最底层的标准库函数是怎么写的?

c++ - 如何使用 Doxygen 记录应用程序源文件

multithreading - 为什么spring不提供线程范围实现?

c++ - 一次加载整个缓存行以避免争用其中的多个元素

android - I/Choreographer : Skipped 33 frames!应用程序可能在其主线程上做太多工作吗?

c++ - boost::multiprecision::uint128_t sizeof 为 24

c++ - 来自任何有效地址的 ipv4 和 ipv6