我有一个程序产生多个线程,每个线程执行一个长期运行的任务.然后主线程等待所有工作线程加入,收集结果并退出.
如果其中一个工作程序发生错误,我希望其余的工作程序正常停止,以便主线程可以在不久之后退出.
我的问题是如何最好地执行此操作,当长期运行的任务的实现由我的代码无法修改的库提供时.
这是系统的简单草图,没有错误处理:
void threadFunc()
{
// Do long-running stuff
}
void mainFunc()
{
std::vector<std::thread> threads;
for (int i = 0; i < 3; ++i) {
threads.push_back(std::thread(&threadFunc));
}
for (auto &t : threads) {
t.join();
}
}
Run Code Online (Sandbox Code Playgroud)
如果长时间运行的函数执行循环并且我可以访问代码,那么只需通过检查每次迭代顶部的共享"keep on running"标志就可以中止执行.
std::mutex mutex;
bool error;
void threadFunc()
{
try {
for (...) {
{
std::unique_lock<std::mutex> lock(mutex);
if (error) {
break;
}
}
}
} catch (std::exception &) {
std::unique_lock<std::mutex> lock(mutex);
error = true;
}
}
Run Code Online (Sandbox Code Playgroud)
现在考虑一下库提供长时间运行的情况:
std::mutex mutex;
bool error; …Run Code Online (Sandbox Code Playgroud) 我正在尝试在Haskell中实现树处理算法,并且(由于这是我的第一个Haskell程序!)正在为数据结构的设计而苦苦挣扎。那里的任何FP专家都可以伸出援手吗?
首先,我将描述算法的重要特征,勾勒出如何使用命令式语言来实现这一点,最后完成到目前为止在Haskell中遇到的绊脚石。
我不会详细描述完整的算法,但是要点如下:
因此,数据结构必须具有以下特征:
如果我要使用命令式语言实现此算法,则解决方案将类似于以下内容。
假设起点是输入树的以下定义:
struct node {
// Identifier for this node, unique within the containing tree
size_t id;
// Label of this node
enum label label;
// Attributes of this node
// An attribute can be assumed to be a key-value pair
// Details of the attributes themselves aren't material to this
// discussion, so the "attribute" type is left opaque
struct attribute **attributes;
size_t n_attributes;
// …Run Code Online (Sandbox Code Playgroud) 有没有更简洁的方法来修改Python 2中URL的某些部分?
例如
http://foo/bar -> http://foo/yah
Run Code Online (Sandbox Code Playgroud)
目前,我这样做:
import urlparse
url = 'http://foo/bar'
# Modify path component of URL from 'bar' to 'yah'
# Use nasty convert-to-list hack due to urlparse.ParseResult being immutable
parts = list(urlparse.urlparse(url))
parts[2] = 'yah'
url = urlparse.urlunparse(parts)
Run Code Online (Sandbox Code Playgroud)
有更清洁的解决方案吗?
我用PyQt制作了一个项目的原型并使其在那里工作,现在我正在尝试将其转换为C++并且遇到了一些问题.
如果我没有放入Q_OBJECT宏,它会编译并运行,但如果我将其注释掉,我会收到以下错误:
Undefined symbols:
"vtable for MapView", referenced from:
MapView::~MapView()in mapview.o
MapView::~MapView()in mapview.o
MapView::MapView(QObject*)in mapview.o
MapView::MapView()in mapview.o
"MapView::staticMetaObject", referenced from:
MapView::MapView(QObject*)in mapview.o
MapView::MapView()in mapview.o
Run Code Online (Sandbox Code Playgroud)
这是标题:
#ifndef MAPVIEW_H
#define MAPVIEW_H
#include <QtGui>
#include <QObject>
class MapView : public QGraphicsScene
{
//Q_OBJECT
public:
MapView();
explicit MapView(QObject *parent = 0);
QGraphicsPixmapItem *mappixmap;
~MapView();
private:
bool dragging;
float offsetX, offsetY, downoffsetX, downoffsetY;
protected:
void mousePressEvent(QGraphicsSceneMouseEvent *event);
void mouseMoveEvent(QGraphicsSceneMouseEvent *event);
void mouseReleaseEvent(QGraphicsSceneMouseEvent *event);
};
#endif // MAPVIEW_H
Run Code Online (Sandbox Code Playgroud)
如果我在这里省略Q_OBJECT宏,那么第二个问题就是Bad Things会发生吗?
是的,我知道将QGraphicsScene称为"视图"是愚蠢的.