【问题标题】:Multithreading Summation using Event使用事件的多线程求和
【发布时间】:2015-12-31 18:39:57
【问题描述】:

我试图强调我在多线程部分的知识,但我在让事件正常运行方面遇到了一些问题。

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

我可以用 Mutex 或 semaphore 做到这一点,但很难用它来使用事件。

    #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

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

【问题讨论】:

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

标签: c++ multithreading event-handling


【解决方案1】:

你得到你要求的行为。您启动两个线程,并且都在等待事件。比您发出信号事件,它们都唤醒并开始(以随机顺序)访问全局变量 yy1。由于数据竞争,您最终会得到完全未定义和不稳定的行为。

【讨论】:

  • SergeyA,我怎样才能让第二个线程在等待函数中等待,直到我从第一个结果中得到结果以实现正确的求和?
  • @OmarHussein,您应该使用互斥锁或类似互斥锁的对象(如临界区)。事件不是解决此问题的正确工具。
  • 我明白你的意思。我正在编写该代码只是为了熟悉事件。我设法使代码也只能通过在 main 方法中打印结果之前添加 sleep() 100 毫秒来工作。
猜你喜欢
  • 2013-04-22
  • 2020-08-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多