我有一个代码,主线程创建2个线程(thread_1和thread_2),我使用pthread_cancel取消thread_2中的thread_1,但在QNX系统中运行时,我在thread_1中创建的数据不会被破坏,但在Linux系统中没有问题。
这是我的测试代码,当我在QNX系统中运行它时,MyClass和MyClass 2对象析构函数没有被调用,所以100 M内存会泄漏;但是在Linux系统中运行它,它会调用MyClass和MyClass 2对象析构函数,为什么会有这样的区别呢?
#include <iostream>
#include <pthread.h>
#include <thread>
using namespace std;
pthread_t thread_id_1;
pthread_t thread_id_2;
class MyClass2
{
public:
MyClass2() {
cout << "Build MyClass2" << endl;
}
~MyClass2() {
cout << "Destory MyClass2" << endl;
}
};
class MyClass
{
public:
MyClass() {
cout << "Build MyClass" << endl;
p = (char *)malloc(1024 * 1024 *100);
}
~MyClass() {
cout << "Destory MyClass" << endl;
free(p);
}
char *p;
};
void func(int i)
{
MyClass2 c2;
std::this_thread::sleep_for(std::chrono::milliseconds(1000));
cout << "thread 1 func:" << i << endl;
}
static void *thread_1(void *arg)
{
MyClass my_class;
int type_value = pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
cout << "thread_1 set cancle type+++++:" << type_value << endl;
for (int i = 0; i < 10; i++) {
func(i);
std::this_thread::sleep_for(std::chrono::milliseconds(1000));
}
return nullptr;
}
static void *thread_2(void *arg)
{
for (int i = 0; i < 10; i++) {
cout << "thread_2:" << i << endl;
std::this_thread::sleep_for(std::chrono::milliseconds(10));
}
int ret = pthread_cancel(thread_id_1);
cout << "otx_thread_2 cancel thread 1 ret:" << ret << endl;
return nullptr;
}
int main(int argc, char *argv[])
{
cout << "Main start" << endl;
pthread_attr_t attr;
pthread_attr_init( &attr );
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
cout << "Main set detch" << endl;
if (pthread_create(&thread_id_1, &attr, thread_1, nullptr) != 0) {
cout << "pthread_create() 1 error" << endl;
return -1;
}
if (pthread_create(&thread_id_2, nullptr, thread_2, nullptr) != 0) {
cout << "pthread_create() 2 error" << endl;
return -1;
}
if (pthread_join(thread_id_2, NULL) != 0) {
cout << "pthread_join() 1 error";
return -1;
}
while (1) {
cout << "Main Loop" << endl;
std::this_thread::sleep_for(std::chrono::milliseconds(1000));
}
return 0;
}
enter image description hereenter image description here显示器
我一遍又一遍地尝试,所以我确认代码没有问题,但我不明白为什么会有这样的差异
1条答案
按热度按时间3vpjnl9f1#
pthread_cancel
超出了C规范的范围。C不指定其行为,也不从C或POSIX继承它。这种差异仅仅是因为QNX和Linux在C++环境中实现
pthread_cancel
的方式不同。我想QNX实现会停止线程,而Linux实现可能会引发一个异常,该异常会解开被取消的线程的堆栈。