我有以下代码:
class Foo {
private:
std::thread thread;
void run();
std::atomic_flag running;
std::thread::native_handle_type native;
public:
Foo(const std::string& filename);
virtual ~Foo();
virtual void doOnChange();
void start();
void quit();
};
#include "Foo.h"
#include <functional>
#include <iostream>
Foo::Foo(const std::string& filename) :
thread(), running(ATOMIC_FLAG_INIT) {
file = filename;
native = 0;
}
Foo::~Foo() {
quit();
}
void Foo::start() {
running.test_and_set();
try {
thread = std::thread(&Foo::run, this);
} catch (...) {
running.clear();
throw;
}
native = thread.native_handle();
}
void Foo::quit() {
running.clear();
pthread_cancel(native);
pthread_join(native, nullptr);
//c++11-style not working here
/*if (thread.joinable()) {
thread.join();
thread.detach();
}*/
}
void Foo::run() {
while (running.test_and_set()) {
numRead = read(fd, buf, BUF_LEN);
.....bla bla bla.......
}
}
Run Code Online (Sandbox Code Playgroud)
我试图在我的程序清理代码中退出这个线程。使用 pthread 有效,但我想知道我是否可以只使用 c++11(没有本机句柄)做更好的事情。在我看来,没有使用 c++11 代码处理所有情况的好方法。正如您在此处看到的,线程在读取系统调用时被阻塞。因此,即使我清除了标志,线程仍将被阻塞并且 join 调用将永远阻塞。所以我真正需要的是一个中断(在这种情况下pthread_cancel)。但是如果我打电话,pthread_cancel我不能再调用 c++11 join() 方法,因为它失败了,我只能调用pthread_join(). 所以看起来标准有一个很大的限制,我错过了什么吗?
编辑:
经过下面的讨论,我更改了 Foo 类实现,用 std::atomic 替换 std::atomic_flag 并使用信号处理程序。我使用信号处理程序是因为在我看来最好有一个通用的基类,在基类中使用自管道技巧太难了,应该将逻辑委托给孩子。最终实现:
#include <thread>
#include <atomic>
class Foo {
private:
std::thread thread;
void mainFoo();
std::atomic<bool> running;
std::string name;
std::thread::native_handle_type native;
static void signalHandler(int signal);
void run();
public:
Thread(const std::string& name);
virtual ~Thread();
void start();
void quit();
void interrupt();
void join();
void detach();
const std::string& getName() const;
bool isRunning() const;
};
Run Code Online (Sandbox Code Playgroud)
cp文件:
#include <functional>
#include <fcntl.h>
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/inotify.h>
#include <Foo.h>
#include <csignal>
#include <iostream>
Foo::Foo(const std::string& name) :
name(name) {
running = false;
native = 0;
this->name.resize(16, '\0');
}
Foo::~Foo() {
}
void Foo::start() {
running = true;
try {
thread = std::thread(&Foo::mainFoo, this);
} catch (...) {
running = false;
throw;
}
native = thread.native_handle();
pthread_setname_np(native, name.c_str());
}
void Foo::quit() {
if (running) {
running = false;
pthread_kill(native, SIGINT);
if (thread.joinable()) {
thread.join();
}
}
}
void Foo::mainFoo() {
//enforce POSIX semantics
siginterrupt(SIGINT, true);
std::signal(SIGINT, signalHandler);
run();
running = false;
}
void Foo::join() {
if (thread.joinable())
thread.join();
}
void Foo::signalHandler(int signal) {
}
void Foo::interrupt() {
pthread_kill(native, SIGINT);
}
void Foo::detach() {
if (thread.joinable())
thread.detach();
}
const std::string& Foo::getName() const {
return name;
}
bool Foo::isRunning() const {
return running;
}
void Foo::run() {
while(isRunning()) {
num = read(.....);
//if read is interrupted loop again, this time
//isRunning() will return false
}
}
Run Code Online (Sandbox Code Playgroud)
正如其他人所说,杀死正在运行的线程是一个坏主意\xe2\x84\xa2。
\n\n但是,在这种情况下,您以某种方式知道线程在读取时阻塞,并希望它停止。
\n\n执行此操作的一个简单方法是使用“自管道技巧”。打开一个管道,并让线程阻塞在select()orpoll()调用上,检查管道的读取端和正在读取的文件描述符。当您希望线程停止时,请将单个字节写入写入描述符。线程醒来,看到管道上的字节,然后可以终止。
这种方法避免了直接终止线程的未定义行为,允许您使用阻塞系统调用来避免轮询,并响应终止请求。
\n正如您在此处看到的,线程在读取系统调用时被阻塞。因此,即使我清除了标志,线程仍将被阻塞并且 join 调用将永远阻塞。
对此的解决方案是std::raise一个信号,例如SIGINTEdit: You need to raise the signal using pthread_kill以便信号将由正确的线程处理。正如您从手册中看到的那样,读取会被信号中断。您必须处理std::signal否则整个过程将过早终止。
在使用 BSD 信号处理而不是 POSIX 的系统上,系统调用默认重新启动而不是在中断时失败。我建议的方法依赖于 POSIX 行为,其中调用设置EINTR和返回。POSIX 行为可以使用siginterrupt显式设置。另一种选择是使用 注册信号处理程序sigaction,除非由标志指定,否则不会重新启动。
后read已经中断,必须检查线程是否应重试读取之前停止。
使用 c++11(甚至可能没有它)不要在线程中调用任何阻塞系统调用
调用阻塞系统调用就好了。如果您希望在不终止进程的情况下终止线程(在有限时间内),那么您不应该调用可能会无限长时间阻塞的不可中断的系统调用。在我的脑海里,我不知道是否有任何系统调用符合这样的描述。
一个最小的例子(除了无限期阻塞read。你可以sleep(100000)用来模拟它):
#include <thread>
#include <iostream>
#include <csignal>
#include <cerrno>
#include <unistd.h>
constexpr int quit_signal = SIGINT;
thread_local volatile std::sig_atomic_t quit = false;
int main()
{
// enforce POSIX semantics
siginterrupt(quit_signal, true);
// register signal handler
std::signal(quit_signal, [](int) {
quit = true;
});
auto t = std::thread([]() {
char buf[10];
while(!quit) {
std::cout << "initiated read\n";
int count = read(some_fd_that_never_finishes, buf, sizeof buf);
if (count == -1) {
if (errno == EINTR) {
std::cout << "read was interrupted due to a signal.\n";
continue;
}
}
}
std::cout << "quit is true. Exiting\n";;
});
// wait for a while and let the child thread initiate read
sleep(1);
// send signal to thread
pthread_kill(t.native_handle(), quit_signal);
t.join();
}
Run Code Online (Sandbox Code Playgroud)
强行杀死线程通常是一个非常糟糕的主意,尤其是在 C++ 中,这可能是std::threadAPI 不为其提供接口的原因。
如果你真的想杀死一个执行线程——在这种情况下这不是必需的,因为你可以安全地中断系统调用——那么你应该使用子进程而不是子线程。杀死子进程不会破坏父进程的堆。也就是说,C++ 标准库不提供进程间 API。