【发布时间】:2018-09-27 16:45:29
【问题描述】:
(首先,对不起我的英语不好。) 我已经为我当前的项目编写了一些测试代码,我相信我编写了低效的代码:我想启动一个新线程(它应该与主线程异步运行 -> 我使用 detach()),之后用户在其键盘上输入了三个键。例如。这个线程应该工作五秒钟,当线程工作时,用户可以输入越来越多的键,并且总是在三个输入之后一个线程应该启动:
#include <iostream>
#include <cstdlib>
#include <thread>
#include <mutex>
using namespace std;
mutex m;
const int MAX_letters = 3;
int letters = MAX_letters;
thread st;
void send() {
cout << "\nsending ... [START] ... " << this_thread::get_id() << "\n";
this_thread::sleep_for(chrono::seconds(5));
cout << "\nsending ... [END] ... " << this_thread::get_id() << "\n";
}
int main() {
while (true) {
if (letters > 0) {
system("PAUSE");
--letters;
} else {
st = thread(send);
st.detach();
letters = MAX_letters;
}
}
return 0;
}
系统(“PAUSE”)应该模拟按键...
现在我的问题是:是否可以为 st 分配一个新线程,即使另一个线程正在运行?
【问题讨论】:
标签: c++ multithreading visual-studio c++11 visual-c++