停止在线程中运行的类方法

Stop class method running in thread

本文关键字:运行 类方法 线程      更新时间:2023-10-16

>我创建了一个名为 Timer 的C++类,它有 3 个方法:

  • 开始()
  • 停止()
  • 打印()

start()方法启用名为run的标志,将其值设置为true

stop()方法禁用标志,将其值设置为false

print()方法,在条件下执行while(),如果run == true,并打印一些休眠半秒的文本。


计时器.hpp

#ifndef TIMER
#define TIMER 1
#include <iostream>
#include <cstdbool>
#include <unistd.h>
class Timer{
private:
bool run;
public:
void start();
void stop();
void print();
};
#endif

定时器.cpp

#include "Timer.hpp"
void Timer::start(){
this->run = true;
this->print();
return;
}
void Timer::stop(){
this->run = false;
return;
}
void Timer::print(){
int counter = 0;
while(this->run == true){
std::cout << counter << std::endl;
counter++;
usleep(500000);
}
return;
}

主.cpp

#include <pthread.h>
#include "Timer.hpp"
void *handler(void *argument){
((Timer *) argument)->start();
return argument;
}
int main(void){
Timer *timer = new Timer();
pthread_t timer_thread;
int mainCounter = 0;
pthread_create(&timer_thread, NULL, handler, (void *) &timer);
while(true){
if(mainCounter == 100){
std::cout << "Stopping..." << std::endl;
timer->stop();
}
std::cout << " => " << mainCounter << std::endl;
mainCounter++;
usleep(50000);
}
return 0;
}

我的问题。

我在主线程中创建了一个条件来处理方法start()的执行,在该条件中,mainCounter获得 100 次迭代后,它会执行timer->stop(),但它不会停止计时器循环。

mainCounter到达第 100 次迭代时,它无法停止线程内的循环。

编译指令是:

g++ Timer.cpp -c 
g++ Timer.cpp main.cpp -o main -lpthread

输出为:

9
=> 90
=> 91
=> 92
=> 93
=> 94
=> 95
=> 96
=> 97
=> 98
=> 99
10
Stopping...
=> 100
=> 101
=> 102
=> 103
=> 104
=> 105
=> 106
=> 107
=> 108
=> 109
11

在线试用!

正如@user4581301所提到的,这将解决问题:

pthread_create(&timer_thread, NULL, handler, (void *) &timer);

应该是

pthread_create(&timer_thread, NULL, handler, (void *) timer);

问题是timer指向分配的Timer类,而&timer指向堆栈上的某个位置。运行线程时,您正在尝试访问run类成员,但由于this指向堆栈,因此您实际上是在读取不正确的值。

其他注意事项:将bool run声明为std::atomic_bool run,或使用任何互斥锁机制来实现线程安全。此外,请始终删除分配的变量:delete timer