gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 03:17:21 26 4
gpt4 key购买 nike

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

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

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

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

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


定时器.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;
}

main.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

Try it online!

最佳答案

如@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++ - 停止在线程中运行的类方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55597881/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com