我正在编写一个通用的抽象类,以便能够根据需要报告任意数量的实例变量的状态.例如,考虑以下无用循环:
int a, b;
for (int i=0; i < 10000; ++i) {
for (int j=0; j < 1000; ++j) {
for (int k =0; k < 1000; ++k) {
a = i;
b = j;
}
}
}
Run Code Online (Sandbox Code Playgroud)
能够看到a和b不必修改循环的值是很好的.在过去,我写过if语句,如下所示:
int a, b;
for (int i=0; i < 10000; ++i) {
for (int j=0; j < 1000; ++j) {
for (int k =0; k < 1000; ++k) {
a = i;
b = j;
if (a % …Run Code Online (Sandbox Code Playgroud) 我有几个工作函数,调用可能会发生错误的附件函数.如果附件功能确定发生了不好的事情,我希望能够停止工作功能,而无需在工作功能中进行多次标记检查.例如,
struct Worker {
bool badhappened = false;
Worker() {
std::thread([&]() {
while ( not badhappened );
// kill the work
}).detach();
}
int WorkComponent {
if ( badhappening() )
badhappened = true;
return someint;
}
void DoWork {
// WorkComponents called several times
}
}
Run Code Online (Sandbox Code Playgroud)
但我不知道该怎么称呼kill the work.DoWork在单独的线程中发生并不是问题,但pthread_kill在C++的线程中似乎没有相应的东西.有没有涉及多次if(badhappened) return;调用的解决方案DoWork?
这里 pthread 在 1013 个线程之后没有被创建。我知道每个进程的线程创建都有限制,但在这里我取消了线程,并且在线程中我还调用了pthread_testcancel()取消点。实际上这里发生了什么?有人可以帮我纠正线程创建失败吗?我是多线程的新手,如果您能为我提供详细的解释,那就太好了。谢谢。
#include<iostream>
#include<pthread.h>
void* t(void*){
while(1){
pthread_testcancel(); //cancellation point?
}
}
main(){
pthread_t id;
int i = 0;
while(1){
++i;
if(pthread_create(&id, 0, t, 0)){
std::cout<<"\n failed to create "<<i; //approx get hit at i=1013
break;
}
if(pthread_cancel(id))
std::cout<<"\n i = "<<i; //not at al executes, pthread_cancell is always successful?
}
}
Run Code Online (Sandbox Code Playgroud)