线程终止

时间:2017-09-06 22:46:39

标签: 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();
}

1 个答案:

答案 0 :(得分:4)

我删除了一些未使用的部分,并将实际条件更改为5.6 7.0 7.1 ,它似乎正如此链接所示:

http://rextester.com/TWHK12491

但是,我没有声称这是绝对正确的,但是它显示了如何使用原子导致读取/写入值的同步可能导致数据竞争。

atomic<bool>