2015-12-31 47 views
0

我想强调我在多线程部分的知识,并且在让事件正常工作时遇到了一些问题。多线程总结使用事件

所以基本上我用两个线程一个线程只是设置某个变量YY1一个,第二个线程应该有一个等待函数来获取YY1的价值,并增加额外的价值,并把结果变量Y2 。

我可以用互斥量或信号量做到这一点,但努力使用事件。

#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 

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

+0

看起来像'C++'。用适当的语言特定标签标记您的问题。 –

回答

0

你得到你要求的行为。你开始你的两个线程,并且都在等待事件。比你发出信号事件,它们都醒来并开始(按照自由度顺序)访问全局变量yy1。由于数据竞赛,你最终会完全没有定义和不稳定的行为。

+0

SergeyA,以及如何让第二个线程在等待函数中等待,直到我从第一个结果中获得结果以实现正确的求和? –

+0

@OmarHussein,你应该使用互斥体或类似互斥体的对象(如关键部分)。事件并不是恰当的工具。 – SergeyA

+0

我明白你的意思了。我正在研究这些代码,以便熟悉事件。我设法使代码也可以工作,只需要在主方法中打印结果之前添加sleep()100毫秒。 –