本帖最后由 mo1230 于 2024-4-3 11:09 编辑
子线程里在循环执行操作,想要在主线程中关闭这个已经处于分离状态的线程。
因为传入的参数是指针,所以想着通过改变这个指针指向的值,从而去关闭子线程。但是失败了,关闭不了,但是通过pthread_kill函数查看线程的状态,却显示线程已经不存在了。。。
这该怎么操作,才能在主线程里关掉子线程。
#include <iostream>
#include <pthread.h>
#include "opencv2/opencv.hpp"
#include "opencv2/core/core.hpp"
#include "opencv2/highgui/highgui.hpp"
struct data
{
bool* run;
int* num;
};
void* thread_func(void *arg)
{
cv::Mat img;
cv::VideoCapture cap(0);
struct data* datas = (struct data*)arg;
int i = *(datas->num);
for (;;)
{
i++;
cap >> img;
if (img.empty())
{
std::cerr << "img is empty..." << std::endl;
continue;
}
if (*(datas->run))
{
std::cout << "thread_func..." << i << img.size() << std::endl;
}else
{
std::cout << "thread_func...end..." << std::endl;
break;
}
}
}
int run()
{
bool running = true;
int i = 0;
pthread_t t_pid;
struct data data_s;
data_s.run = &running;
data_s.num = &i;
pthread_create(&t_pid, NULL, thread_func, &data_s);
pthread_detach(t_pid);
_sleep(2000);
while (running)
{
i++;
std::cout << "run ..." << i << std::endl;
_sleep(100);
if (i > 100)
{
running = false;
pthread_join(t_pid, NULL);
// std::cout << "arg: " << *arg << std::endl;
// pthread_cancel(t_pid);
// pthread_join(t_pid, NULL);
// _sleep(0);
int state = pthread_kill(t_pid, 0);
if (state == ESRCH)
{
std::cout << "thread is not exit..." << std::endl;
}else if (state == EINVAL)
{
std::cout << "thread is invalid..." << std::endl;
}else
{
std::cout << "thread is alive..." << std::endl;
}
return -1;
}
}
}
int main()
{
run();
std::cout << "main...end..." << std::endl;
while (1)
{
// 其他操作
}
return 0;
}
|