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

C++ 全局变量+;计算函数发生的次数,c++,multithreading,C++,Multithreading,我已经定义了一个全局变量,counter,它应该在主线程执行的辅助函数中的while循环的每次迭代中递增。当全局变量more设置为1时,工作进程发生,当“more”设置为0时停止 然而,由于while循环没有发生,全局变量似乎没有改变。请帮帮我。我在这个阶段非常绝望 在main外部声明全局变量 //Variable which controls whether worker procedure continues to perform and when it terminates

我已经定义了一个全局变量,
counter
,它应该在主线程执行的辅助函数中的while循环的每次迭代中递增。当全局变量
more
设置为1时,工作进程发生,当“more”设置为0时停止

然而,由于while循环没有发生,全局变量似乎没有改变。请帮帮我。我在这个阶段非常绝望

在main外部声明全局变量

    //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;
u应将全局变量声明为volatile

因为它是由多个线程访问的,而编译器所做的任何优化都可能导致这种情况

volatile int count = 0;
相似的更多

volatile int more = 0;

两个问题:1)在启动线程之前,more不会设置为1。如果他们已经执行了while循环,但什么也没执行呢?2) 什么是说线程在1秒睡眠时间内启动?他们可能是,但是你确认了吗?而且,这个代码似乎不是你实际使用的代码。缺少一些定义。如何声明更多?[OT]:我不认为
srand
是线程安全的,可以做你想做的事情……如果你可以访问C++11,多线程就更容易处理了!volatile不是多核上线程安全的解决方案。例如,请参见:
count
应为
std::atomic
volatile int more = 0;