【发布时间】:2018-09-02 06:06:09
【问题描述】:
我希望main 函数在事件发生时停止function_(在本例中为 1 毫秒后)。我遇到的问题是function_ 立即重新锁定互斥锁,而不让main 函数获取它。
#include <thread>
#include <mutex>
#include <iostream>
#include <chrono>
using namespace std;
void function_(volatile bool *ptrStop, mutex *ptrMtx) {
for (int i = 0; i < 10; i++) {
ptrMtx->lock();
if (*ptrStop) {
ptrMtx->unlock();
return;
}
//doSomething();
this_thread::sleep_for(chrono::milliseconds(1));
cout << "Iteration " << i << endl;
ptrMtx->unlock();
//this_thread::sleep_for(chrono::milliseconds(1));
}
return;
}
int main() {
volatile bool stop = 0;
mutex mtx;
thread functionThread(function_, &stop, &mtx);
this_thread::sleep_for(chrono::milliseconds(1));
mtx.lock();
stop = 1;
mtx.unlock();
cout << "Changed boolean variable value" << endl;
functionThread.join();
system("pause");
return 0;
}
我得到以下输出:
Iteration 0
Iteration 1
Iteration 2
Iteration 3
Iteration 4
Iteration 5
Iteration 6
Iteration 7
Iteration 8
Iteration 9
Changed boolean variable value
我想要的是只对 function_only 进行 1 或 2 次迭代(因此让 main 使用互斥锁)。我怎样才能做到这一点 ?我听说过std::condition_variable,但我想不出一种方法来制作我想要的东西。
此外,如果 doSomething() 未注释并且需要很长时间才能返回,是否有一种简单的方法可以杀死线程或强制它加入而不修改 doSomething 函数中的内容?
【问题讨论】:
-
你能展示一下你用
std::condition_variable做了什么吗?它应该是你想要使用的。 -
Volatile 不适用于多线程目的 (stackoverflow.com/questions/35345899/…)。
-
现在线程可以在主线程到达
mtx.lock()之前完成运行function_的所有迭代。 -
你读过
std::condition_variable的文档吗?应该很容易扩展这个例子,让它做你想做的事。你只需要一个停止标志和一个工作线程中的循环。 -
不要使用
lock和unlock。酌情使用std::unique_lock或std::lock_guard。
标签: c++ multithreading c++11 visual-c++