i wanna provide a class, that holds a buffer while reading in some data (udp packets or from a file). Everything is fine if i start my thread from the main, but in this case i want to avoid, that the user has to set up a new thread for himself.
so here is my code as simple as i could make it:
class DataCollector
{
void startCollect()
{
std::thread t1(readSource);
}
bool readSource()
{
while(1)
{
// read some data for storage
}
}
}
int main()
{
DataCollector myDataCollector;
myDataCollector.startCollect();
while(1)
{
// do some other work, for example interpret the data
}
return 0;
}
now i need your help. How can i call this thread inside startCollect?
edit1:
here is my example of how it works NOW!
// ringbuffertest.cpp : Definiert den Einstiegspunkt für die Konsolenanwendung.
//
#include "stdafx.h"
#include <thread>
#include <Windows.h>
class DataCollector
{
private:
//std::thread collecterThread;
public:
DataCollector(){}
void startCollect()
{
readSource();
}
bool readSource()
{
while (1)
{
printf("Hello from readSource!\n");
Sleep(1000);
}
return false;
}
};
int _tmain(int argc, _TCHAR* argv[])
{
DataCollector myDataCollector;
std::thread t1(&DataCollector::startCollect, std::ref(myDataCollector));
t1.join();
return 0;
}
but as i said i would like to hide the thread call inside my startCollect function.
Before destroying an active thread object, it must either be joined (waiting for the thread to finish, then cleaning up its resources) or detached (left to run and clean itself up when finished).
So you could either make the thread a member variable, so that it can be joined later:
void startCollect()
{
this->thread = std::thread(&DataCollector::readSource, this);
}
void waitForCollectToFinish()
{
this->thread.join();
}
or you could detach it, if you don't need the ability to wait for it to finish, and have some other way of signalling that data is available:
void startCollect()
{
std::thread([this]{readSource();}).detach();
}
You might also look at higher-level concurrency facilities, such as std::async and std::future. These might be more convenient than dealing with threads directly.
Related
I have one main thread that will send an async job to the task queue on the other thread. And this main thread can trigger a destroy action at any time, which could cause the program to crash in the async task, a piece of very much simplified code like this:
class Bomb {
public:
int trigger;
mutex my_mutex;
};
void f1(Bomb *b) {
lock_guard<std::mutex> lock(b->my_mutex); //won't work! Maybe b have been destructed!
sleep(1);
cout<<"wake up.."<<b->trigger<<"..."<<endl;
}
int main()
{
Bomb *b = new Bomb();
b->trigger = 1;
thread t1(f1, b);
sleep(1);
//lock here won't work
delete b;//in actual case it is triggered by outside users
t1.join();
return 0;
}
The lock in f1 won't work since the destructor can be called first and trying to read mutex will crash. Put lock in destructor or before the delete also won't work for the same reason.
So is there any better way in this situation? Do I have to put mutex in the global scope and inside destructor to solve the issue?
In code, my comment looks like this :
#include <future>
#include <mutex>
#include <iostream>
#include <chrono>
#include <thread>
// do not use : using namespace std;
class Bomb
{
public:
void f1()
{
m_future = std::async(std::launch::async,[this]
{
async_f1();
});
}
private:
void async_f1()
{
using namespace std::chrono_literals;
std::lock_guard<std::mutex> lock{ m_mtx };
std::cout << "wake up..\n";
std::this_thread::sleep_for(1s);
std::cout << "thread done.\n";
}
std::future<void> m_future;
std::mutex m_mtx;
};
int main()
{
{
std::cout << "Creating bomb\n";
Bomb b; // no need to use unecessary new
b.f1();
}
std::cout << "Bomb destructed\n";
return 0;
}
I am fairly new to C++ and very new to using mutex. I am trying to implement a thread safe queue by #ChewOnThis_Trident from this answer.
Essentially I have different threads adding messages to a queue and I need to preserve the order they are being added. However the messages require some conditional modifications before being added. In the real code listeners on separate threads call unique "handleMessage" functions that modify the message before adding to them to the queue. A separate thread checks to see if messages are in the queue and handles them in order. In the full code, I know the listeners are receiving the messages in the correct order, but they are failing to add them to the queue in the correct order.
I think the problem is there is some time elapsing between when a message is received and if it is being modified, causing messages to fall out of order.
For practical reasons in the real code, I can't do these modifications inside of "Safequeue::enqueue".
In my example two threads can add to the queue. One thread reads from it. The "message" in this case is a random int. "UsesQ" handles adding to the queue, and message modification (Ex. makes all ints odd).
I think another mutex is needed when "UsesQ::addQ" is called, but it would need to be shared across all the threads and I'm not sure if I am not sure how to implement it.
In the example I am struggling of thinking of a way to test if the order is correct.
Here is the example:
#include <queue>
#include <mutex>
#include <condition_variable>
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <assert.h>
#include <pthread.h>
#include <unistd.h>
class SafeQueue
{// A threadsafe-queue.
public:
SafeQueue(void)
: q()
, m()
, cv()
{}
~SafeQueue(void)
{}
// Add an element to the queue.
void enqueue(int i)
{
std::lock_guard<std::mutex> lock(m);
q.push(i);
cv.notify_one();
}
// Get the "front"-element.
// If the queue is empty, wait till a element is avaiable.
int dequeue(void)
{
std::unique_lock<std::mutex> lock(m);
while(q.empty())
{
// release lock as long as the wait and reaquire it afterwards.
cv.wait(lock);
}
int val = q.front();
q.pop();
return val;
}
private:
std::queue<int> q;
mutable std::mutex m;
std::condition_variable cv;
};
class UsesQ
{
private:
int readVal;
int lastReadVal = 1;
public:
SafeQueue & Q;
UsesQ(SafeQueue & Q): Q(Q){};
~UsesQ(){};
void addQ(int i)
{
if(i% 2 == 0)
{
i++;//some conditional modification to the initial "message"
}
Q.enqueue(i);
}
void removeQ()
{
readVal = Q.dequeue();
}
};
void* run_add(void* Ptr)
{
UsesQ * UsesQPtr = (UsesQ *)Ptr;
for(;;)
{
int i = rand();//simulate an incoming "message"
UsesQPtr->addQ(i);
}
pthread_exit (NULL);
return NULL;
}
void* run_remove(void* Ptr)
{
UsesQ * UsesQPtr = (UsesQ *)Ptr;
for(;;)
{
UsesQPtr->removeQ();
}
pthread_exit (NULL);
return NULL;
}
int main()
{
SafeQueue Q;
UsesQ * UsesQPtr = new UsesQ(std::ref(Q));
pthread_t thread1;
pthread_create(&thread1, NULL, run_add, UsesQPtr);
pthread_t thread2;
pthread_create(&thread2, NULL, run_add, UsesQPtr);
pthread_t thread3;
pthread_create(&thread3, NULL, run_remove, UsesQPtr);
while(1)
{
usleep(1);
printf(".\n");
}
};
Complied with the pthread tag
g++ main.cpp -pthread
Thank you for any help.
I want to create a thread that can be interrupted while waiting (it waits data from other processes and I want to stop the process in nice way).
I've read the 9.2 part of C++ Concurrency in Action 2nd Edition, and I've tried to implement that ideas, but I've some problem and I don't know where to check.
This is my code based on that example:
#include <iostream>
#include <stdexcept>
#include <thread>
#include <mutex>
#include <atomic>
#include <condition_variable>
#include <future>
// Exception that should be raised when there's an interruption.
// It's raised when the thread is interrupted, so we can catch
// it and finish the thread execution.
class InterruptedException : public std::runtime_error {
public:
InterruptedException(const std::string& message) : std::runtime_error(message) {}
virtual ~InterruptedException() {}
};
// Interrupt flag. This class represents a local-thread flag that
// tells if the thread is interrupted or not.
class InterruptFlag {
public:
InterruptFlag() :
m_threadConditionVariable(nullptr),
m_threadConditionVariableAny(nullptr) {}
void set() {
m_flag.store(true, std::memory_order_relaxed);
std::lock_guard<std::mutex> lk(m_setClearMutex);
if (m_threadConditionVariable) {
m_threadConditionVariable->notify_all();
}
else if (m_threadConditionVariableAny) {
m_threadConditionVariableAny->notify_all();
}
}
template <typename Lockable>
void wait(std::condition_variable_any& cv, Lockable& lk) {
struct CustomLock {
InterruptFlag* m_self;
Lockable& m_lk;
CustomLock(InterruptFlag* self, std::condition_variable_any& cond, Lockable& lk) :
m_self(self),
m_lk(lk) {
m_self->m_setClearMutex.unlock();
m_self->m_threadConditionVariableAny = &cond;
}
void unlock() {
m_lk.unlock();
m_self->m_setClearMutex.unlock();
}
void lock() {
std::lock(m_self->m_setClearMutex, lk);
}
~CustomLock() {
m_self->m_threadConditionAny = nullptr;
m_self->m_setClearMutex.unlock();
}
};
CustomLock cl(this, cv, lk);
InterruptPoint();
cv.wait(cl);
InterruptPoint();
}
void setConditionVariable(std::condition_variable& cv) {
std::lock_guard<std::mutex> lk(m_setClearMutex);
m_threadConditionVariable = &cv;
}
void clearConditionVariable() {
std::lock_guard<std::mutex> lk(m_setClearMutex);
m_threadConditionVariable = nullptr;
}
bool isSet() const {
return m_flag.load(std::memory_order_relaxed);
}
private:
std::atomic<bool> m_flag;
std::condition_variable* m_threadConditionVariable;
std::condition_variable_any* m_threadConditionVariableAny;
std::mutex m_setClearMutex;
};
// Thread-local interrupt flag instance. The variable should be
// created for every thread, since it's thread_local.
thread_local InterruptFlag ThisThreadInterruptFlag;
// Convenience class for cleaning the flag due to RAII.
struct ClearConditionVariableOnDestruct {
~ClearConditionVariableOnDestruct() {
ThisThreadInterruptFlag.clearConditionVariable();
}
};
// Function that throws the exception that tells that the thread
// is interrupted. For doing it checks the state of ThisThreadInterruptFlag.
void InterruptionPoint() {
if (ThisThreadInterruptFlag.isSet()) {
throw InterruptedException("Interrupted");
}
}
// Function that must be used inside the thread function body for waiting.
// It waits for the condition variable, when it notifies from other threads,
// but it also notifies if the thread is interrupted.
void InterruptibleWait(std::condition_variable& cv, std::unique_lock<std::mutex>& lk) {
InterruptionPoint();
ThisThreadInterruptFlag.setConditionVariable(cv);
ClearConditionVariableOnDestruct guard;
InterruptionPoint();
cv.wait_for(lk, std::chrono::milliseconds(1));
InterruptionPoint();
}
// This class represents the interruptible thread. It adds a interrupt()
// method that when called interupts the thread execution, if it's waiting
// at some point where InterruptibleWait function is locked.
class Interruptible {
public:
template <typename FunctionType>
Interruptible(FunctionType f) {
std::promise<InterruptFlag*> p;
m_internalThread = std::thread([f, &p]() {
p.set_value(&ThisThreadInterruptFlag);
try {
f();
}
catch (InterruptedException) {
}
});
m_flag = p.get_future().get();
}
void join() {
m_internalThread.join();
}
void detach() {
m_internalThread.detach();
}
bool joinable() const {
return m_internalThread.joinable();
}
void interrupt() {
if (m_flag) {
m_flag->set();
}
}
private:
std::thread m_internalThread;
InterruptFlag* m_flag;
};
std::mutex mtx;
std::unique_lock<std::mutex> lk(mtx);
int main(int argc, char* argv[]) {
std::cout << "Interrupting thread example" << std::endl;
bool test = false;
std::condition_variable cv;
auto f = [&cv, &test]() {
test = true;
InterruptibleWait(cv, lk);
// Since it locks forever, it should never reach this point.
test = false;
};
Interruptible interruptibleThread(f);
std::this_thread::sleep_for(std::chrono::milliseconds(30));
// We interrupt the function while it's blocked in InterruptibleWait
interruptibleThread.interrupt();
interruptibleThread.join();
std::cout << "test value is " << std::boolalpha << test << ". It should be true." << std::endl;
return 0;
}
Basically I create a Interruptible class representing a thread that can be interrupted. I interrupt it during its execution by calling its interrupt() method. The thread can be interrupted if it's locked with in a InterruptibleWait function call. This function behave like a std::condition.wait(), in fact it wants a reference to it, but it also handle the interruption flag.
If I start the program. I obtain an error from Visual Studio when running.
I don't know what I'm doing wrong. What should I do in order to make InterruptibleWait work correctly?
My best guess based on the given information:
The exception isn't caught in the thread entry point function, and escapes that function. When this happens in a thread started by std::thread, abort is called for you (indirectly through std::terminate) by the std::thread implementation, as required by the standard. To fix this, try catching all exceptions in the function passed to std::thread.
See the cppreference articles on std::thread and std::terminate
On Ubuntu, I have a shared library mylibrary.so, with a function AlphaFunction. I want to load this function in C++ using dlopen, and then call it in two different threads. However, this is giving me run-time errors, presumably because the two threads are both trying to access the same memory where the function is stored.
The library itself controls a robot arm via USB, and the actual run-time error I get is: LIBUSB_ERROR_NO_DEVICE returned by the Write operation.
I know how to use std::atomic for dealing with shared variables, but what about a shared function?
For example:
void Foo(int (*FooFunction)())
{
while(true)
{
FooFunction();
}
}
void Bar(int (*BarFunction)())
{
while(true)
{
BarFunction();
}
}
int main()
{
void* api_handle = dlopen("mylibrary.so", RTLD_NOW|RTLD_GLOBAL);
int (*MoveRobot)() = (int (*)()) dlsym(api_handle, "Move");
std::thread t1(Foo, MoveRobot);
std::thread t2(Bar, MoveRobot);
t1.join();
t2.join();
return 0;
}
I've had a look at the comments. Here's a solution that covers all concerns:
the robot library is not thread safe, and
all calls to the robot library must be on the same thread
This answer proposes a solution in which a third thread is started up which acts as the robot request marshaller. The other threads post tasks to this thread's queue, which are executed one at a time, with the result of the call being returned via a future on which the caller can wait.
#include <thread>
#include <mutex>
#include <queue>
#include <future>
#include <functional>
// these definitions here just to make the example compile
#define RTLD_NOW 1
#define RTLD_GLOBAL 2
extern "C" void* dlopen(const char*, int);
extern "C" void* dlsym(void*, const char*);
struct RobotCaller final
{
RobotCaller()
{
_library_handle = dlopen("mylibrary.so", RTLD_NOW|RTLD_GLOBAL);
_Move = (int (*)()) dlsym(_library_handle, "Move");
// caution - thread starts. do not derive from this class
start();
}
void start()
{
_robot_thread = std::thread([this]{
consume_queue();
});
}
~RobotCaller() {
if (_robot_thread.joinable()) {
std::unique_lock<std::mutex> lock(_queue_mutex);
_should_quit = true;
lock.unlock();
_queue_condition.notify_all();
_robot_thread.join();
}
// close library code goes here
}
std::future<int> Move()
{
return queue_task(_Move);
}
private:
void consume_queue() {
;
for(std::unique_lock<std::mutex> lock(_queue_mutex) ; !_should_quit ; lock.lock()) {
_queue_condition.wait(lock, [this]{
return _should_quit || (!_task_queue.empty());
});
if (!_task_queue.empty()) {
auto task = std::move(_task_queue.front());
_task_queue.pop();
lock.unlock();
task();
}
}
}
std::future<int> queue_task(int (*f)())
{
std::packaged_task<int()> task(f);
auto fut = task.get_future();
std::unique_lock<std::mutex> lock(_queue_mutex);
_task_queue.push(std::move(task));
return fut;
}
private:
// library management
void* _library_handle = nullptr;
int (*_Move)() = nullptr;
// queue management
std::thread _robot_thread;
std::queue<std::packaged_task<int()>> _task_queue;
bool _should_quit = false;
std::mutex _queue_mutex;
std::condition_variable _queue_condition;
};
void Foo(std::function<std::future<int>()> FooFunction)
{
while(true)
{
// marshal the call onto the robot queue and wait for a result
auto result = FooFunction().get();
}
}
void Bar(std::function<std::future<int>()> BarFunction)
{
while(true)
{
// marshal the call onto the robot queue and wait for a result
auto result = BarFunction().get();
}
}
int main()
{
RobotCaller robot_caller;
std::thread t1(Foo, std::bind(&RobotCaller::Move, &robot_caller));
std::thread t2(Bar, std::bind(&RobotCaller::Move, &robot_caller));
t1.join();
t2.join();
return 0;
}
Using C++, I would like to start a thread from a void method and then return before the thread may have finished. For example:
#include <thread>
using namespace std;
void longFunc(){
//stuff
}
void startThread(){
thread t(longFunc);
}
int main(void){
startThread();
//lots of stuff here...
return 0;
}
When the startThread() finishes, t tries to be deleted, and fails. How can I do this?
If you really want a fire-and-forget pattern, you can just detach from the thread:
void startThread(){
thread t(longFunc);
t.detach();
}
Or if you need to join the thread (which is most often a reasonable thing), you could simply return an std::thread object by value (thread wrappers are moveable):
std::thread startThread()
{
return std::thread(longFunc);
}
Anyway, you may consider launching the thread through std::async() and returning a future object instead. This would be exception-safe, since exceptions thrown in the launched thread will be swallowed by the future object, and thrown again in the main thread when you invoke get() on it:
#include <thread>
#include <future>
void longFunc()
{
//stuff
}
std::future<void> startThread()
{
return std::async(std::launch::async, longFunc);
}
int main(void)
{
auto f = startThread();
//lots of stuff here...
// For joining... (wrap in a try/catch block if you are interested
// in catching possible exceptions)
f.get();
}