全局变量+计数函数发生的次数

时间:2014-01-30 18:17:23

标签: c++ multithreading

我已经定义了一个全局变量counter,它应该在由main中的线程执行的worker函数中的while循环的每次迭代中递增。当全局变量more设置为1并在"更多"时停止工作程序。设置为0.

但是,全局变量似乎没有改变,因为while循环没有发生。请帮我。我现阶段绝望了!

在主

之外声明全局变量
    //Variable which controls whether worker procedure continues to perform and when it terminates
    int more;

    //Static variable to keep track of the number of transfers which have taken place 
    //while threads allow worker procedure to be performed
    int counter;

在main中设置线程和工作程序以及更改more和counter

的值
    //Create a thread handle to control threads
threadH[thread] = CreateThread(NULL, 0, worker, (LPVOID)thread, 0, NULL);
//Set number of transfers to zero
counter = 0;
    //Threads run until variable more is set to 0
more = 1;
    //Main thread sleeps for 10,000ms (10 seconds)
Sleep(1000);
//Set more = 0 so worker procedures being executed by threads terminate
more = 0;
    cout << "Counter = " << count << endl;

线程执行的工作程序 //工作程序

DWORD WINAPI worker(LPVOID thread)
{
    //Seed random number generator
    srand((int)thread);

    //Worker procedure continually transfers a random amount of money 
    //from one random account to another random account until the variable "more" is set to 1
    while (more == 1)
    {
            counter++;

        //InterlockedExchangeAdd((LONG*)&counter, 1);
    }

    return 0;
}

1 个答案:

答案 0 :(得分:0)

  

你应该将全局变量声明为 volatile

因为由多个线程访问,并且编译器完成的任何优化可能导致这种情况。

volatile int count = 0;

Similalry了解更多。

volatile int more = 0;