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();
}
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;
}
Related
in below code snippet it looks like notification from producer thread to consumer thread is not reaching once producer produce an single item and due to this behavior once producer has finished generating items equivalent to buffer size then only consumer has started consuming items . Can anybody suggest How we should approach to fix this issue using semaphore.
#include <iostream>
#include <queue>
#include <semaphore.h>
#include <thread>
#include <functional>
const int BUFFER_SIZE = 3;
class Buffer {
public:
sem_t sem_full;
sem_t sem_empty;
std::queue<int> buffer;
Buffer() {
sem_init(&sem_full, 0, BUFFER_SIZE);
sem_init(&sem_empty, 0, 0);
}
void producer() {
while (true) {
sem_wait(&sem_full);
int item = rand() % 10;
buffer.push(item);
std::cout << "Producer added " << item << std::endl;
sem_post(&sem_empty);
if (buffer.size() == BUFFER_SIZE) {
std::cout << "Buffer is full, terminating producer thread" << std::endl;
return;
}
}
}
void consumer() {
while (true) {
sem_wait(&sem_empty);
int item = buffer.front();
buffer.pop();
std::cout << "Consumer removed " << item << std::endl;
sem_post(&sem_full);
if (buffer.empty()) {
std::cout << "Buffer is empty, terminating consumer thread" << std::endl;
return;
}
}
}
};
int main() {
Buffer buffer;
std::thread producer(std::bind(&Buffer::producer, &buffer));
std::thread consumer(std::bind(&Buffer::consumer, &buffer));
producer.join();
consumer.join();
return 0;
}
you need to use binary semaphore here to achieve this behavior without using condition variable to synchronize this.
#include <iostream>
#include <queue>
#include <semaphore.h>
#include <thread>
#include <functional>
#include <condition_variable>
#include <mutex>
#include <atomic>
const int BUFFER_SIZE = 4;
class Buffer {
public:
sem_t sem_full;
sem_t sem_empty;
std::queue<int> buffer;
std::condition_variable cv;
std::mutex m;
int buffer_full_count {0};
Buffer() {
sem_init(&sem_full, 0, 1);
sem_init(&sem_empty, 0, 0);
}
void producer() {
while (true) {
sem_wait(&sem_full);
if (buffer_full_count == BUFFER_SIZE) {
std::cout << "Buffer is full, terminating producer thread" << std::endl;
return;
}
std::unique_lock <std::mutex> lock(m);
int item = rand() % 10;
buffer.push(item);
buffer_full_count++;
std::cout << "Producer added " << item << std::endl;
std::this_thread::sleep_for(std::chrono::seconds(1));
sem_post(&sem_empty);
}
}
void consumer() {
while (buffer_full_count != BUFFER_SIZE) {
sem_wait(&sem_empty);
std::unique_lock <std::mutex> lock(m);
int item = buffer.front();
buffer.pop();
std::cout << "Consumer removed " << item << std::endl;
sem_post(&sem_full);
}
}
};
int main() {
Buffer buffer;
std::thread producer(std::bind(&Buffer::producer, &buffer));
std::thread consumer(std::bind(&Buffer::consumer, &buffer));
producer.join();
consumer.join();
return 0;
}
I'm getting a crash when calling interrupt() on an outer boost::thread, which runs an inner boost::thread, which is connected to a thread_guard. It's not crashing when calling join() manually on the inner thread.
Crash:
terminate called after throwing an instance of 'boost::thread_interrupted'
Source:
https://gist.github.com/elsamuko/6e178c37fa2cf8742cb6bf512f2ff866
#include <iostream>
#include <thread>
#include <boost/thread/thread.hpp>
#include <boost/thread/thread_guard.hpp>
#define LOG( A ) std::cout << A << std::endl;
void double_interrupt() {
boost::thread outer([] {
boost::thread inner([]{
while(true) {
std::this_thread::sleep_for(std::chrono::milliseconds(1));
}
});
{
std::this_thread::sleep_for(std::chrono::milliseconds(1));
LOG("Interrupting inner");
boost::thread_guard<boost::join_if_joinable> guard(inner); // crashes
// inner.join(); // works
}
});
LOG("Interrupting outer");
outer.interrupt();
outer.join();
}
int main(int argc, char* argv[]) {
LOG("Start");
double_interrupt();
LOG("End");
return 0;
}
Compile & Run:
http://coliru.stacked-crooked.com/a/46c512bf9a385fff
I'm running on Ubuntu 18.04. with g++ 7.5.0 and got the latest boost 1.78.0.
I opened this issue on github, too: https://github.com/boostorg/thread/issues/366
You're mixing std::thread and boost::thread.
Only Boost Thread knows about interruption points. Use that to fix:
Live On Coliru
#include <iostream>
#include <thread>
#include <boost/thread.hpp>
#include <boost/thread/thread_guard.hpp>
void double_interrupt() {
boost::thread outer([] {
boost::thread inner([] {
while (true) {
boost::this_thread::sleep_for(boost::chrono::milliseconds(1));
}
});
{
boost::this_thread::sleep_for(boost::chrono::milliseconds(1));
std::cout << "Interrupting inner" << std::endl;
boost::thread_guard<boost::join_if_joinable> guard(inner);
}
});
std::cout << "Interrupting outer" << std::endl;
outer.interrupt();
outer.join();
}
int main() {
std::cout << "Start" << std::endl;
double_interrupt();
std::cout << "End" << std::endl;
}
Prints
Start
Interrupting outer
End
I got a solution. The problem was, that the join() of the thread_guard waits for the inner thread with a condition_variable::wait(). condition_variable::wait() itself checks, if it's interruptible and throws an exception.
The solution is to use a custom thread_guard with disable_interruption:
#include <iostream>
#include <thread>
#include <boost/thread.hpp>
#include <boost/thread/thread_guard.hpp>
#define LOG( A ) std::cout << A << std::endl;
void work() {
size_t sum = 0;
for(int i = 0; i < 1E7; ++i) { sum += 1; }
LOG("work: " << sum);
}
// helper struct to interrupt a boost::thread within a boost::thread
struct non_interruptable_interrupt_and_join_if_joinable {
template <class Thread>
void operator()(Thread& t) {
if(t.joinable()) {
boost::this_thread::disable_interruption di;
t.interrupt();
t.join();
}
}
};
void double_interrupt() {
boost::thread outer([] {
boost::thread inner([] {
while(true) {
boost::this_thread::interruption_point();
work();
}
});
{
boost::thread_guard<non_interruptable_interrupt_and_join_if_joinable> guard(inner);
LOG("Interrupting inner");
}
});
LOG("Interrupting outer");
outer.interrupt();
outer.join();
}
int main() {
LOG("Start");
double_interrupt();
LOG("End");
}
Run here:
http://coliru.stacked-crooked.com/a/a365e40a2bd574cc
This is my minimal, reproducible example
#include <memory>
#include <chrono>
#include <thread>
#include <iostream>
#include <functional>
class BaseClass {
public:
void do_func() {
while(true) {
std::cout << "doing stuff" << std::endl;
std::this_thread::sleep_for(std::chrono::seconds(1));
}
}
};
int main() {
auto obj = std::make_unique<BaseClass>();
std::thread t(&BaseClass::do_func, obj.get());
std::this_thread::sleep_for(std::chrono::seconds(5));
std::cout << "reset called!" << std::endl;
obj.reset();
std::this_thread::sleep_for(std::chrono::seconds(5));
std::cout << "going out of scope" << std::endl;
t.join();
return 0;
}
I was expecting the object to be deleted after reset is called. Even the code cannot exit because the while loop is blocking, which is understandable. I need to delete the object after a particular event, and cannot wait till the unique_ptr goes out of scope. If I change the do_func to
void do_func() {
std::cout << "doing stuff" << std::endl;
std::this_thread::sleep_for(std::chrono::seconds(20));
}
then it is the expected behaviour.
Edit:
Based on your comments I have updated my code to
#include <memory>
#include <chrono>
#include <thread>
#include <iostream>
#include <functional>
class BaseClass {
public:
BaseClass() : x(1) {
dummy = std::make_shared<SomeClass>();
}
void do_func() {
while(true) {
std::cout << "doing stuff " << dummy->do_stuff(x) << std::endl;
x++;
std::this_thread::sleep_for(std::chrono::seconds(1));
}
}
private:
int x;
class SomeClass {
public:
int do_stuff(int x) {
return x * x;
}
};
std::shared_ptr<SomeClass> dummy;
};
int main() {
auto obj = std::make_unique<BaseClass>();
std::thread t(&BaseClass::do_func, obj.get());
std::this_thread::sleep_for(std::chrono::seconds(5));
std::cout << "reset called!" << std::endl;
obj.reset();
std::this_thread::sleep_for(std::chrono::seconds(5));
std::cout << "going out of scope" << std::endl;
t.join();
return 0;
}
And now the function does print garbage values. Does that mean I need to explicitly delete dummy in the destructor?
The simplest way to synchronize these two threads would be to use std::atomic_bool
#include <atomic>
class BaseClass {
public:
std::atomic_bool shouldContinueWork = true;
void do_func() {
while(shouldContinueWork) {
std::cout << "doing stuff" << std::endl;
std::this_thread::sleep_for(std::chrono::seconds(1));
}
}
};
int main() {
auto obj = std::make_unique<BaseClass>();
std::thread t(&BaseClass::do_func, obj.get());
std::this_thread::sleep_for(std::chrono::seconds(5));
obj->shouldContinueWork = false; //the thread will not do anything more after this, but the sleep will need to end on it's own
std::cout << "stopping work!" << std::endl;
// do not remove the object before join is called - you don't know if it will be still accessed from the other thread or not
// obj.reset();
std::this_thread::sleep_for(std::chrono::seconds(5));
std::cout << "going out of scope" << std::endl;
t.join();
// here it is safe to remove the `obj`, main thread is surely the only thread that accesses it
// (but it goes out of scope anyway)
return 0;
}
This solution doesn't take into account stopping the work midway (i.e. whole loop iteration must always be performed) and is generally prone to having a few more or less iterations of work - it should be precise enough when you have sleep of 1s, but with smaller sleep it won't guarantee any exact number of iterations, take that into account. std::condition_variable can be used for more precise control of thread synchronization.
Thanks for all your quick responses! Let me know if this is a good solution
#include <memory>
#include <chrono>
#include <thread>
#include <iostream>
#include <functional>
class BaseClass {
public:
BaseClass() : x(1) {
dummy = std::make_shared<SomeClass>();
}
virtual ~BaseClass() {
dummy.reset();
}
void do_func() {
while(dummy) {
std::cout << "doing stuff " << dummy->do_stuff(x) << std::endl;
x++;
std::this_thread::sleep_for(std::chrono::seconds(1));
}
}
private:
int x;
class SomeClass {
public:
int do_stuff(int x) {
return x * x;
}
};
std::shared_ptr<SomeClass> dummy;
};
class DerivedClass : public BaseClass {
};
int main() {
auto obj = std::make_unique<DerivedClass>();
std::thread t(&BaseClass::do_func, obj.get());
std::this_thread::sleep_for(std::chrono::seconds(5));
std::cout << "reset called!" << std::endl;
obj.reset();
std::this_thread::sleep_for(std::chrono::seconds(5));
std::cout << "going out of scope" << std::endl;
t.join();
return 0;
}
The behaviour is now as expected.
I am following Boost multithreading tutorial here
. Following section 18.13, I try creating a class containing multiple threads as follows:
#define _CRT_SECURE_NO_WARNINGS
#include <ctime>
#include <iostream>
#include <string>
#include <queue>
#include <boost/array.hpp>
#include <boost/bind.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/asio.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/thread.hpp>
#include <boost/thread/thread.hpp>
#include <boost/chrono.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
using boost::asio::ip::udp;
using std::cout;
using std::cin;
using std::endl;
using std::string;
using namespace std;
class MultiTask
{
private:
boost::thread_group threads; // thread group
boost::thread* thread_main; // main thread
boost::thread* thread_output; // output thread
boost::thread* thread_input; // input thread
boost::mutex stopMutex;
bool stop;
int i_in, i_out, i_main;
string userInput;
public:
// constructor
MultiTask()
{
thread_main = new boost::thread(boost::ref(*this));
thread_output = new boost::thread(&MultiTask::Callable_Out, this, 1000, boost::ref(i_out));
thread_input = new boost::thread(&MultiTask::Callable_In, this, 1000, boost::ref(i_out), boost::ref(userInput));
//threads.add_thread(thread_main); // main thread = 0 // will throw -> boost thread: trying to join itself
threads.add_thread(thread_output); // output thread = 1
threads.add_thread(thread_input); // input thread = 2
stop = false;
i_in = 0;
i_out = 0;
i_main = 0;
userInput = "";
}
// destructor
~MultiTask()
{
// stop all threads
Stop();
// show exit message
cout << "Exiting MultiTask." << endl;
}
// start the threads
void Start()
{
// Wait till they are finished
threads.join_all();
}
// stop the threads
void Stop()
{
// warning message
cout << "Stopping all threads." << endl;
// signal the threads to stop (thread-safe)
stopMutex.lock();
stop = true;
stopMutex.unlock();
// wait for the threads to finish
threads.interrupt_all();
threads.join_all();
}
void Callable_Out(int interval, int& count)
{
while (1)
{
//cout << "Callable_Out [" << count++ << "]" << endl;
boost::this_thread::sleep(boost::posix_time::millisec(interval));
boost::this_thread::interruption_point();
}
}
void Callable_In(int interval, int& count, string& userInput)
{
while (1)
{
cout << "Callable_In [" << count++ << "]. Enter message: ";
getline(cin, userInput);
boost::this_thread::sleep(boost::posix_time::millisec(interval));
boost::this_thread::interruption_point();
}
}
// Thread function
void operator () ()
{
while (1)
{
//cout << "Main [" << i_main++ << "]." << endl;
//cout << "Main [" << i_main++ << "]. " << userInput << endl;
if (userInput == "STOP")
{
try
{
this->Stop();
}
catch(exception e)
{
cout << e.what() << endl;
}
}
boost::this_thread::sleep(boost::posix_time::millisec(1000));
boost::this_thread::interruption_point();
}
}
};
int main()
{
MultiTask mt;
mt.Start();
}
However, VS throws two of these errors:
Severity Code Description Project File Line Suppression State
Error C2198 'void (__cdecl *)(boost::posix_time::millisec,int &,std::string &)': too few arguments for call mycpp c:\boost_1_66_0\boost\bind\bind.hpp 259
Can someone please help? This is from section 18.13. Also, I do not see where to input the arguments for CallableFunction() in that example. How can it be done in my case? Thanks.
In tutorial CallableFunction function takes only one parameter, it is passed as second parameter in thread constructor new boost::thread(&CallableFunction, i);.
In your case Callable_Out takes 2 parameters, one is missing, you should call
thread_output = new boost::thread(&Callable_Out, boost::posix_time::millisec(0), boost::ref(i_out));
and for Callable_In you call
thread_input = new boost::thread(&Callable_In, boost::posix_time::millisec(1), boost::ref(i_out), boost::ref(userInput));
I'm using Boost::thread to implement an InterruptibleThread class, while getting segmentation fault during execution. Any idea?
The source and the output are under below.
interruptiblethread.h
#ifndef INTERRUPTIBLETHREAD_H
#define INTERRUPTIBLETHREAD_H
#include <boost/thread.hpp>
#include <boost/thread/future.hpp>
#include <boost/thread/tss.hpp>
class InterruptFlag
{
public:
inline void set()
{
boost::lock_guard<boost::mutex> guard(_mtx);
_set = true;
}
inline bool is_set()
{
std::cout << "is_set()" << std::endl;
boost::lock_guard<boost::mutex> guard(_mtx);
std::cout << "is_set() end" << std::endl;
return _set;
}
private:
boost::mutex _mtx;
bool _set;
};
extern boost::thread_specific_ptr<InterruptFlag> this_thread_interrupt_flag;
class InterruptibleThread
{
public:
template<typename FunctionType>
InterruptibleThread(FunctionType f)
{
boost::promise<InterruptFlag*> p;
_internal_thread = boost::thread([f, &p]()
{
p.set_value(this_thread_interrupt_flag.get());
f();
});
_interrupt_flag = p.get_future().get();
}
inline void interrupt()
{
if (_interrupt_flag != nullptr)
{
_interrupt_flag->set();
}
}
private:
boost::thread _internal_thread;
InterruptFlag* _interrupt_flag;
};
#endif // INTERRUPTIBLETHREAD_H
interruptiblethread.cpp
#include <iostream>
#include <functional>
#include "interruptiblethread.h"
using std::cout; using std::endl;
using std::function;
boost::thread_specific_ptr<InterruptFlag> this_thread_interrupt_flag;
struct thread_interrupted {};
void interruption_point()
{
cout << "interruption_point()" << endl;
if (this_thread_interrupt_flag->is_set())
{
cout << "is_set" << endl;
throw thread_interrupted();
}
}
void foo()
{
while (true)
{
cout << "iterate" << endl;
try
{
interruption_point();
} catch (const thread_interrupted& interrupt)
{
cout << "catch thread_interrupted" << endl;
break;
}
}
}
int main()
{
InterruptibleThread int_thread(foo);
int_thread.interrupt();
while (true) {}
}
Output:
➜ build ./main
iterate
interruption_point()
is_set()
[1] 44435 segmentation fault ./main
this_thread_interrupt_flag is not initialized. Please initialize it correctly as described here
Your call to is_set is UB.