停止在线程中运行的类方法
Stop class method running in thread
>我创建了一个名为 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
。
相关文章:
- 如果C++类在类方法中具有动态分配,但没有构造函数/析构函数或任何非静态成员,那么它仍然是POD类型吗
- 在静态库中嵌入类方法
- 如何制作一个将函数作为参数的类方法
- 从父类方法返回子类对象
- 使用用户定义的参数调用future/async并调用类方法
- 重载类方法的不明确调用
- 单独定义模板化嵌套类方法的正确语法
- 绑定派生类方法C++从实例范围之外的分隔 std::function 变量调用
- 如何访问由共享指针保存的类方法?
- 将子类方法声明为基类的友元
- 我的模板类方法返回错误类型?
- 类方法 - 数据结构中 For 循环的运行时错误
- 停止在线程中运行的类方法
- 初始化期间的运行时类方法替换
- 在运行时C 上覆盖相同的类方法
- 在其他方法之前运行的C 类方法
- C++继承 - 在子类中运行父方法
- pthread以并行方式运行类实例的方法
- 在另一个类方法中运行类方法
- 在运行时不使用虚函数从基类方法访问派生类方法