I created two thread and canceled one of them before joining them:
#include <iostream>
#include <pthread.h>
#include <assert.h>
#include <unistd.h>
#include <signal.h>
using namespace std;
void *func_1 (void *arg)
{
for (;;) {
cout << "1" << endl;
sleep (1);
}
return NULL;
}
void *func_2 (void *arg)
{
for (;;) {
cout << "222" << endl ;
sleep (1);
}
return NULL;
}
int main (void)
{
pthread_t thread_1, thread_2;
assert (pthread_create (&thread_1, NULL, func_1, NULL) == 0);
assert (pthread_create (&thread_2, NULL, func_2, NULL) == 0);
pthread_cancel (thread_1);
pthread_join (thread_1, NULL);
pthread_join (thread_2, NULL);
}
The output is:
1
222
It is in blocking status.
I find both cout.bad()
and cout.fail()
is true. If using printf()
, it works well.
It can works well if execute cout.clear()
.
I wonder why the cout is in bad state.
8
pthread_cancel (thread_1);
pthread_cancel
is a C library POSIX function.
It is incompatible with any non-trivial C++ class. pthread_cancel
knows absolutely nothing, whatsoever, about any C++ class, its constructors or its destructors.
Such as std::cout
from the C++ library.
Using pthread_cancel
, with an execution thread that uses C++ classes, like std::cout
results in undefined behavior.
I wonder why the cout is in bad state.
Because you cannot use cout
with C library POSIX threads, in this manner. There are no solutions, there are no workarounds (well, technically it might be possible to use it safely but with a lot, a lot of work and a huge pile of code, and you don’t want to go there).
You will not find much information about POSIX threads in any modern C++ textbook which will, instead, present and explain how to use std::thread
in modern C++ code.
1