Simple code snippet hanging forever:
#include <csignal>
#include <mutex>
#include <print>
#include <iostream>
void *routine(void *arg) {
pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, nullptr);
pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, nullptr);
std::istream &input = std::cin;
int value;
std::cout << "Reading" << std::endl;
input >> value;
std::cout << "Reading done" << std::endl;
return nullptr;
}
int main() {
pthread_t th;
pthread_create(&th, nullptr, routine, nullptr);
usleep(1000000);
std::cout << "Cancelling thread" << std::endl;
pthread_cancel(th);
std::cout << "Cancelled" << std::endl;
pthread_join(th, nullptr);
std::cout << "Joined" << std::endl;
}
with output
Reading
Cancelling thread
Cancelled
routine is trying to read value from standard input and I’d like to cancel it.
MacOS, G++ or Clang
I would expect routine thread to be cancelled when pthread_cancel is called but it is not