使用事件的多线程求和

时间:2015-12-31 18:39:57

标签: c++ multithreading event-handling

我试图强调我在多线程部分的知识,并且我在使事件运作良好方面存在一些问题。

所以基本上我使用两个线程一个线程只是将某个变量yy1设置为1,第二个线程应该有一个wait函数来获取yy1的值并添加一个额外的值并将结果放在变量y2中。

我可以使用Mutex或信号量,但努力使用它的事件。

    #include <process.h>
#include <windows.h>
#include <iostream>
#include <math.h>

using namespace std;
void ThreadFunction1(void *pParam);
void ThreadFunction2(void *pParam);


HANDLE h_Event1;
int yy1= 0;
int y2 = 0;

void main(void)                             // Primary Thread
{
    h_Event1 = CreateEvent(NULL,            // Security Attributes
        FALSE,              // Manual Reset: no/auto , Auto Reset when the event released
        FALSE,              // Initial Statse: not set , not occupied 
        NULL);              // Name: no


    _beginthread(ThreadFunction1,           // Pointer to Thread Function
        0,                  // Stack Size set automatically
        (void*)&yy1);   // Frequency


    _beginthread(ThreadFunction2,           // Pointer to Thread Function
        0,                  // Stack Size set automatically
        (void*)&y2);    // Frequency

    SetEvent(h_Event1);
    CloseHandle(h_Event1);

    cout << yy1<<endl;
    cout << y2 << endl;

}

void ThreadFunction1(void *pParam)          // Secundary Thread
{
    int xx1;

    xx1 = (int)*(int*)pParam;

    WaitForSingleObject(h_Event1, INFINITE);
    xx1 = 1;
    *(int*)pParam = xx1;
    Sleep(100);
    _endthread();
}

void ThreadFunction2(void *pParam)          // Secundary Thread
{
    int xx1;

    xx1 = (int)*(int*)pParam;

    WaitForSingleObject(h_Event1, INFINITE);
    xx1 = 1+ (yy1);
    *(int*)pParam = xx1;
    Sleep(10);

    _endthread();
}

输出是:

0
2

注意: 我知道在这种情况下使用多线程可能没有意义,但我只是试图在事件使用上使用。

1 个答案:

答案 0 :(得分:0)

你得到了你所要求的行为。你开始你的两个线程,两个都在等待事件。比你发出信号事件,他们都醒来并开始(按照radom顺序)访问全局变量yy1。你最终得到的是由于数据竞争导致的完全未定义和不稳定的行为。