Boost thread questions - c++

I am trying to do the followings
class a{
public:
void Start();
void Tick();
bool IsTimeOut;
};
void a::Start()
{
boost::thread thread1(boost::bind(&a::Tick,this));
}
void a::Tick()
{
while(!IsTimeOut)
{
boost::this_thread::sleep(boost::posix_time::millisec(1000));
}
}
My environment is vs2005 and win7.
However, I always got the access violation in the debug.

An access violation in this case would indicate that the thread is running beyond the lifetime of the a object.
IsTimeOut needs to either be atomic or protected by a mutex if it is written by another thread, otherwise your program might not work correctly, but this shouldn't cause the access violation.
You are destroying the boost::thread object immediately, and thus detaching the thread, so you have no way of waiting for it to finish. I would suggest storing the thread object as a member variable of a, and either joining with it in the destructor of a or providing an explicit wait() member function that joins with the thread.

IsTimeOut should be volatile if accessed from multiple threads, i.e.
volatile bool IsTimeOut;
Take a look at this DDJ article.
If you show more of your code and also explain how the IsTimeOut is changed it might be easier to say what goes wrong. In general, it looks like you have multiple threads and the first creates a, but what does that thread do then? Will a go out of scope and thus be destroyed? If so, then the timer thread will for sure have an access violation as the object is no longer available.

Related

Is std::exception_ptr thread safe?

I have a worker thread that is constantly running, created & managed through a std::thread. At the top level of my worker thread, I have a try/catch block with a while loop inside it. If an exception leaks through to the top level of the thread, I catch it and store it in a std::exception_ptr, which is a member of the class that also owns the non-static thread function:
// In class header (inside class declaration)
std::exception_ptr m_threadException;
// In class CPP file
void MyClass::MyThreadFunction()
{
try {
while (true) {
// Do thread stuff
}
}
catch (std::exception const& e) {
m_threadException = std::current_exception();
}
}
Once the thread dies due to this kind of exception, my class (which is also primarily used by the main thread) doesn't know it yet. My plan was to add thread checkpoints to the start of all the class's main functions, like so:
void MyClass::SomethingMainThreadCalls()
{
if (m_threadException) {
std::rethrow_exception(m_threadException);
m_threadException = nullptr; // Somehow reset it back to null; not sure if this will work
}
// Do normal function stuff
}
Assuming this is even a good idea, there's a possible race condition between when my main thread is checking if the exception_ptr is null (when calling SomethingMainThreadCalls()) and when the worker thread assigns to it. I haven't found any information (haven't checked the C++11 draft yet) about whether or not this is inherently thread safe (guaranteed by the standard) or if I am responsible for thread synchronization in this case.
If the latter, is using std::atomic a good idea to keep it simple? Example:
std::atomic<std::exception_ptr> m_threadException;
Something like that? I'd be interested in recommendations and information on best practice here.
There is no special statement about exception_ptr with regards to its thread safety in the standard. As such, it provides the default standard guarantee: accessing separate instances are fine, accessing the same instance is not.
I would suggest using atomic<bool> instead (if for no other reason than that exception_ptr is not trivially copyable and therefore can't be put in an atomic<T>) to let the other code know that the exception_ptr has been set. You'll be fine so long as:
You set m_threadException before setting the flag
You read m_threadException after checking the flag
You use the appropriate load/store memory orders to set/check the flag. The defaults are fine
You only write m_threadException exactly once.
The standard doesn't specify what is the implementation of std::exception_ptr, so the thread safeness of std::exception_ptr is also unspecified.
just wrap the exception pointer with some lock and the code will be fine.
Just tried to do this, but std::atomic requires a trivially copyable type, std::exception_ptr is not. You should get compilation error as I do (when using MSVC VS2019, C++14).

Put all database operations in a specific thread using Qt

I have a console application where after a timeout signal, a 2D matrix (15*1200) should be parsed element-by element and inserted to a database. Since the operation is time-consuming, I perform the insertion in a new thread using QConcurrent::run.
However, due to timeout signals, several threads may start before one finished, so multiple accesses to the database may occur.
As a solution, I was trying to buffer all database operations in a specific thread, in other words, assign a specific thread to the database class, but do not know how to do so.
Your problem is a classical concurrent data analysis problem. Have you tried using std::mutex? Here's how you use it:
You create some variable std::mutex (mutex = mutual exclusion) that's accessible by all the relevant threads.
std::mutex myLock;
and then, let's say that the function that processes the data looks like this:
void processData(const Data& myData)
{
ProcessedData d = parseData();
insertToDatabase(d);
}
Now from what I understand, you're afraid that multiple threads will call insertToDatabase(d) simultaneously. Now to solve this issue, simply do the following:
void processData(const Data& myData)
{
ProcessedData d = parseData();
myLock.lock();
insertToDatabase(d);
myLock.unlock();
}
Now with this, if another thread tries to access the same function, it will block until another all other threads are finished. So threads are mutually excluded from accessing the call together.
More about this:
Caveats:
This mutex object must be the same one that all the threads see, otherwise this is useless. So either make it global (bad idea, but will work), or put it in a the class that will do the calls.
Mutex objects are non-copyable. So if you include them in a class, you should either make the mutex object a pointer, or you should reimplement the copy constructor of that class to prevent copying that mutex, or make your class noncopyable using delete:
class MyClass
{
//... stuff
MyClass(const MyClass& src) = delete;
//... other stuff
};
There are way more fancier ways to use std::mutex, including std::lock_guard and std::unique_lock, which take ownership of the mutex and do the lock for you. This are good to use if you know that the call insertToDatabase(d); could throw an exception. In that case, using only the code I wrote will not unlock the mutex, and the program will reach a deadlock.
In the example I provided, here's how you use lock_guard:
void processData(const Data& myData)
{
ProcessedData d = parseData();
std::lock_guard<std::mutex> guard(myLock);
insertToDatabase(d);
//it will unlock automatically at the end of this function, when the object "guard" is destroyed
}
Be aware that calling lock() twice by the same thread has undefined behavior.
Everything I did above is C++11.
If you're going to deal with multiple threads, I recommend that you start reading about data management with multiple threads. This is a good book.
If you insist on using Qt stuff, here's the same thing from Qt... QMutex.

C++ thread safety of static resources

Say I have the following classes:
public class Item {
public:
CString name;
int id;
UINT type;
bool valid;
void invalidate(){
valid = false;
}
...
}
public class itemPool {
public:
static std::vector<Item*> items ;
void invalidateOfType(UINT type){
for( auto iter : items )
if ( iter->type == type )
iter->invalidate();
}
...
}
Can I call the "invalidateOfType(UINT type)" - method from different threads?
Is there any possibility of "undefined behaviour" ? In other words, can I use static resources from in multiple threads ( make parallel calls to that resource ) ?
Static resources are no different than any shared resources. Unless their methods are thread-safe, they should not be called from multiple threads simultaneously. In your particular case, it boils down to the question of invalidate() being thread safe. Iterating over vector itself is thread-safe.
Quite unexpectedly (to me!) the question turned out into something very interesting and educational. Following are points of interest to remember here. In explaining those, I will take the code at the face value. I will also operate under the assumption (actually clarified by OP in some of the comments) that no code is READING while the invalidation takes place.
The code as written would iterate over the same vector at the same time. Since iterating the vector which is not modified during iteration is thread safe, this part is thread safe and needs no further discussion.
The second question is 'can two or more threads execute invalidateOfType for the same type at the same type'? If the answer is NO - every thread has it's own type - than again, the code is 100% thread safe, since same objects are not accessed from more than one thread and no further discussion is neccessary.
If the answer to the above question is 'YES', than we have a conondrum. Effectively it boils down to the question 'when two or more threads set the same memory location to the same value at the same time, is it going to produce unexpected results'? Precise reading of standards does not give a straight answer.
No, you cannot. This could result in two threads executing valid = false; at the same time on the same valid. It is not permissible to modify an object in one thread while another thread is, or might be, accessing it. (To be sure, check the docs for the particular threading model or library you are using, but most have this rule.)
I would consider this okay on Windows, because everyone does it. It's unlikely that some subsequent change to the platform will break everyone's code. I wouldn't do this on POSIX platforms because the documentation is pretty clear that it's not allowed and it's not commonly done.
If your question is, calling invalidateOfType() simultaniously from different threads lead to data curruption (one thread reading the other writing to the same object), then the answer is yes.
But you can protect the resource, in this example the items vector, with a std::mutex and std::lock_guard like:
class itemPool {
public:
static std::vector<Item*> items;
static std::mutex items_mutex;
void invalidateOfType(UINT type) {
std::lock_guard< std::mutex > scoped_lock(items_mutex);
for (auto iter : items)
if (iter->type = type)
{
iter->invalidate();
}
}
...
}
If thread1 is just executing invalidateOfType and thread2 does a call to invalidateOfType, then thread2 has to wait until thread1 has left the function and the items_mutex is unlocked.
Do this with every resource you share accross threads to prevent corruption.
Can I call the "invalidateOfType(UINT type)" - method from different threads?
Dear god, no! Simply touching that array from another thread while the invalidateOfType function is running is sufficient to crash your program instantly. There's no locks anywhere.
At the very least you should lock (ie mutex) access to the array itself.

C++ Singleton in multithread

I am new to multi thread programming, yet I am studying a big project by someone else. In the code he has a singleton class and it has some public member variable and a member mutex. He used this singleton in different threads like:
singleton::instance()->mutex.lock();
singleton::instance()->value = getval();
singleton::instance()->mutex.release();
Is this the safe way to do it?
If not what is the proper way of read/write the value in singleton?
No it is not safe to do so.
The problem is that the mutex is handed out to the user. There is no guarantee that this lock will be released. For example, what happens if getval() would throw an exception ?
The proper way to do so would be to embed mutex use inside the API of your singleton. For example:
void singleton::setvalue(int val) { // example supposing value is an int
std::lock_guard<std::mutex> mylck (mutex);
value = val;
}
In this example, a local std::lock_guard is used. This object locks the mutex and unlocks it on destruction. This makes sure that in any case the mutex will be unlocked, whenever function returns and even if an exception would be thrown.
Note: If all you are doing is getting a variable like return variable; then it is safe to do even without the lock.
About the code. Assuming the lock is implemented correctly then it is safe to do anything before release is called

How to solve unreleased lock issue in C++

Someone please help me solve deadlock issues in c++ if possible with reference or examples.
Scenario would be like below.
Thread1 is locked by mutex and doing some operation, thread2 and thread3 are in waiting state for thread1 to unlock to access the resource.
Some abort/unexpected thing happened -- thread1 was terminated and didn't get the unlock, thread2 and thread3 are still waiting.
How to save the main thread (mean nothing should happen to main thread) in such situations.
Please throw some light how to solve such issues in c++.
Thanks,
Sheik
Some abort/unexpected thing happened
Use s.th. like std::lock_guard to prevent 'hanging' locks due to exceptions or forgotten/unexpected, but necessary unlock() operations.
The principle is pretty simple and you can easily implement it for any mechanism that uses a pair of methods that correspond together in a 'lock/unlock' manner:
class LockObject // E.g. mutex or alike
{
public:
// ...
void lock();
void unlock();
};
Bind the guard classes constructor to a reference to the lock object's instance and call lock() in the constructor and unlock() in the destructor:
template<typename T>
class LockGuard
{
public:
LockGuard(T& lockObject)
: lockObject_(lockObject)
{
lockObject_.lock();
}
~LockGuard()
{
lockObject_.unlock();
}
private:
T& lockObject_;
};
Use LockGuard like this:
// Some scope providing 'LockObject lockObject'
{ LockGuard<LockObject> lock(lockObject)
// Do s.th. when lockObject is locked
} // Call of lockObject.unlock() is guaranteed at least here, no matter what
// (exception, goto, break, etc.) caused leaving the block's scope.
Generally threads should not terminate unexpectedly. You may try using try/catch blocks. If you still want to free resources when a thread terminates unexpectedly, you may create a monitor thread that waits for the termination of the first thread.
On Windows, you can use something as ::WaitForSingleObject(m_htThread, INFINITE).
Once the 1st thread had been terminated, you may proceed with freeing abandoned locks.
Maybe you'll want to add some flag which indicates if the termination was graceful.
You'll probably also have to remember which thread is locking which object.
As said, I wouldn't recommend using such method, but on extreme cases.
The way to solve deadlocks in any language or platform is always the same.
Always acquire the locks in the same order.
EDIT: However you have misdescribed your problem. This is not a deadlock. A deadlock is a circular chain of locks. This is simply an unreleased lock, i.e. a lock leak. The solution is the same as any other resource leak: don't. In C++ that means releasing resources in destructors, and ensuring that destructors are called. Somehow your thread has terminated without doing that. Find that problem and fix it.