S
S
simply_user2015-02-23 13:09:33
C++ / C#
simply_user, 2015-02-23 13:09:33

Why does a static variable in a class have the same value in all threads?

Hello!
If I understand correctly a static class variable, since it is on the stack, each thread should have its own, and changing this variable in one thread should not change its value in another. Then why does the presented code work? The meaning of this code is that when the static flag variable of the SomeClass class changes to true, other threads exit the loop according to the condition. But after all, changing a static variable in one thread should not affect its value in another, right?
Thanks in advance.

#include <thread>
#include <mutex>
#include <iostream>
#include <locale>

using namespace std;

mutex printMutex;

#define PRINT(text) { lock_guard<mutex> guardPrintMutex(printMutex); cout<<text<<endl;}

class SomeClass
{
public:
  static bool flag;
};

bool SomeClass::flag = false;

void main()
{
  setlocale(LC_ALL, "Russian");

  thread th1([]()
  {
    PRINT("Первый поток начат");
    for (int i = 0; i < 100000; i++)
    {
      if (i == 99999)
      {
        SomeClass::flag = true;
        PRINT("Первый поток завершён.");
      }
    }
  });

  thread th2([]()
  {
    PRINT("Второй поток начат");
    while (true)
    {
      if (SomeClass::flag)
      {
        PRINT("Второй поток завершён.");
        break;
      }
    }
  });

  thread th3([]()
  {
    PRINT("Третий поток начат");
    while (true)
    {
      if (SomeClass::flag)
      {
        PRINT("Третий поток завершён.");
        break;
      }
    }
  });

  th1.join();
  th2.join();
  th3.join();
  system("pause");
}

Answer the question

In order to leave comments, you need to log in

4 answer(s)
A
Alexey Huseynov, 2015-02-23
@kibergus

Static variables are located not on the stack, but in the data area. In the same place as global variables. In order to declare thread-specific variables, C++11 introduced the thread_local specifier .

S
Sergey Lagner, 2015-02-23
@lagner

If I understand correctly a static class variable, since it is on the stack, each thread should have its own

Not right

V
Vladimir Martyanov, 2015-02-23
@vilgeforce

Static members of a class are the same for all instances of the class.

A
AxisPod, 2015-02-23
@AxisPod

Now we take the C++ book for dummies and read it.
And secondly, using a static variable to stop a thread is a shot in the foot. With and without optimization, you will catch different behavior. At a minimum, you need to mark it as volatile (in this case, when using static, the variable will be subject to optimization, as a result, it will again work incorrectly). And if you use C++11, then std::atomic_flag or std::atomic is better.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question