线程终止

Terminating while thread

本文关键字:终止 线程      更新时间:2023-10-16

我无法关闭线程。我忘了做某事吗?该线程似乎正在保存我用于关闭的值,然后再也没有检查它是否已更改。这是一些具有相同效果的示例代码:

#include "stdafx.h"
#include "Windows.h"
#include <iostream>
#include <thread>
class test {
private:
    bool user_wants_thread = true;
    bool time_to_close = false;
public:
    bool set_timetoclose(bool in) {
        time_to_close = in;
        if (time_to_close == in) {
            return true;
        }
        return false;
    }
    void function() {
        while (user_wants_thread) {
            // CODE
            std::cout << time_to_close;
            Sleep(100);
            if (time_to_close) {
                goto close;
            }
        }
    close:
        Sleep(1);
    }
};
int main() {
    test t;
    std::thread thread_func(&test::function, t);
    Sleep(1000);
    bool success;
    do {
        success = t.set_timetoclose(true);
    } while (!success);
    thread_func.join();
    std::cout << "Closed";
    std::cin.get();
}

我删除了一些未使用的零件,并将实际条件更改为atomic<bool>,并且似乎可以正常工作,如此链接所示:

http://rextester.com/twhk12491

我并不是说这是绝对正确的,但是它表明了如何使用原子原因跨读/写入可能导致数据竞赛的值同步。

#include "Windows.h"
#include <iostream>
#include <thread>
#include <atomic>
class test {
public:
    std::atomic<bool> time_to_close = false;
    test()=default;
    void function() {
        while (!time_to_close) {
            std::cout << "Running..." << std::endl;
            Sleep(100);
        }
        std::cout << "closing" << std::endl;
    }
};
int main() {
    test t;
    std::thread thread_func([&t](){t.function();});
    Sleep(500);
    t.time_to_close = true;
    std::cout << "Joining on thread" << std::endl;
    thread_func.join();
    std::cout << "Closed";
    return 0;
}