c++ - 线程终止

标签 c++ multithreading

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

#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

不过,我并不是说这是绝对正确的,但它显示了使用 atomic 如何导致跨读取/写入值的同步,这可能导致数据竞争。

#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;
}

关于c++ - 线程终止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46085379/

相关文章:

c++ - 暴露私有(private)内部类大小

c++ - 为什么互斥锁和条件变量可以轻松复制?

c++ - boost::lockfree::spsc_queue 忙等待策略。有阻塞流行音乐吗?

c++ - 防止 C++ 中的交错

javascript - 使用 web worker 进行 api 调用

c++ - 在 Mac 上无法将 Pylon(Basler) SDK 与 Qt 链接

c++ - 如何在 C++ Builder 6 中从应用程序源创建 dll?

c++ - 存在线程错误的 SFML 程序

Java:生产者-消费者两个线程停止工作,卡住

python - 为什么本地启动的线程不会在每次迭代结束时终止?