vidsac
vidsac

Reputation: 74

Terminating while thread

I can't close my thread. Am I forgetting to do something? The thread seems like it's saving the value I'm using for close, and then never checks if it has changed. Here is some example code that has an identical effect:

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

Upvotes: 0

Views: 74

Answers (1)

xaxxon
xaxxon

Reputation: 19751

I removed some unused parts and changed the actual condition to be an atomic<bool> and it seems to work as shown on this link:

http://rextester.com/TWHK12491

I'm not claiming this is absolutely correct, however, but it shows how using the atomic causes synchronization across reads/writes to the value which could result in a data race.

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

Upvotes: 4

Related Questions