i am having a bit of a struggle with a mutli-threaded program i am trying to create. Its a pretty simple application im just creating in order to see how multi-threading works and so on :)
okay so the thing is i have 2 threads and 1 variable, Thread1 is supposed to print the variable they have in common once every second or so(time does not really matter, its just an example) then while Thread1 sleeps for 1 second Thread2 comes in and edits its value to something completely different and the next time Thread1 runs its supposed to print the new value assigned by thread2 allthough this is not happening :/ what is happening is that Thread1 prints the default constructors value even tho it got changed, its kind of hard to explain in words so i have linked the simple example below, i am hoping someone can help me understand this. Btw i know i should be using a mutex or a critical section since im sharing a resources between the two, but since they never run at the same time and its just a simple example i just left it out.
Main.cpp
int _tmain(int argc, _TCHAR* argv[])
{
Printer printer;
std::thread thread1(&Printer::SetMessage, printer, printer); //Sets the new value of "New Message"
std::thread thread2(&Printer::Print, printer, &printer); //Prints the message using printf()
while(true) {
Sleep(5000); //i have a beakpoint here just to look at the variables once every 5 sec.
}
return 0;
}
Printer.cpp
void Printer::Print(Printer &obj) {
while(true) {
printf(obj.Message.c_str());
Sleep(1000);
}
}
void Printer::SetMessage(Printer &obj) {
while(true) {
Sleep(10000);
obj.Message = "New Message";
}
}
Printer::Printer(void){
this->Message = "YOLO";
}
Printer::~Printer(void){}
so i simply want the value of Message to get updated in all other threads, i mean they are using the same object and changing the value in the same damn object, but why will it not stay changed between threads ??? im so confused :S i have only seen examples that do it in the same class, it got so much more complicated(in my brain) once i used multiple classes.
You pass printer to the thread constructor, which copies the object, so each thread has a different Printer, not the same object.
In fact, your code shouldn't even compile, but std::thread in Visual Studio has a bug that allows this to happen (and that's ignoring the fact you wrote &printer which would pass a pointer, and Printer::print(Printer& obj) doesn't take a pointer).
To pass a reference to the thread function you need to wrap the object using std::ref which creates a reference_wrapper<Printer> that forwards the argument as a reference to the new thread, instead of making a copy and passing the copy to the new thread:
std::thread thread2(&Printer::Print, std::ref(printer), std::ref(printer));
However, even if you fix that, your code has undefined behaviour, because it is unsafe and invalid for two threads to read/write the same memory location without using mutexes or atomic operations to do the updates safely.
Btw i know i should be using a mutex or a critical section since im sharing a resources between the two, but since they never run at the same time and its just a simple example i just left it out.
Perhaps the thing you've missed is that even though you put sleep instructions in each method in the hope that each thread would be only active while the other is sleeping, there are no guarantees that the program will execute that way.
The only safe way of blocking a thread while the other is active is to coordinate them using a lock.
You should also pass the data by reference to the threads.
Related
When I call joinThread I occasionally get an std::system_error thrown of with "invalid argument" at the join call. The error appears to only show up when I compile with gcc, and it is not consistently reproducible, i.e. it occasionally occurs and not predictably. Does anyone know what could cause such an error?
Below is a reduced version of my code.
class exampleClass
{
public:
exampleClass()
{
}
~exampleClass()
{
joinThread();
}
void doWork()
{
joinThread();
workThread = std::thread(&exampleClass::threadFunction, this);
}
void joinThread()
{
if(workThread.joinable()) workThread.join();
}
protected:
void threadFunction()
{
std::cout << "Do something that requires time..." << std::endl
}
std::thread workThread;
}
Any help would be greatly appreciated.
Since you did not provide an example, where this error occurs, I can only speak from my own experience. There are some things you should consider, in order to avoid such an error:
Is your thread just default constructed, resp. did you initialize it with a valid callback function?
Is your thread detached?
Have you moved your thread?
Is the thread trying to access an already reserved resource? Think about possible deadlock sources! Maybe you got stuck somewhere. (But afaik the thread should still be joinable anyway.)
Does a friend method or class try to access/use/join the thread?
I recently forgot to pass a function to a thread, which I had default constructed in order to use it later. This happened due to a conditional initialization procedure. So regarding your example class above:
Your workThread is default constructed upon constructing an object of exampleClass. A callback function is only passed, if you call doWork(). You have made sure that the thread is only joined, if it is in a joinable state. Upon destruction of your object this is also guaranteed. Thus, the most likely reason I can think of, why this might fail, is if you have somewhere a friend. You haven't put that in your example though, but maybe you neglected this, because you wanted to present a reduced form.
Maybe also a look here: http://cppatomic.blogspot.com/2018/05/modern-effective-c-make-stdthread.html might help.
I have a function to calculate the value in real time
void task() {
while(true) {
...//calculate value(value will change every loop)
}
}
In the main thread, my code is as follow, i want to use the real time value which i got from task thread,
int main() {
...
while(true) {
int v = value;//value is calculated from task thread in real time
....
}
}
The main Thread will cost about 0.5s one loop, so i want to get the lastest value to update the v in next loop,How can i do this?
It's my first time to use Thread in c++,i don't know how to write the code.Can someone help me.Thanks in advance!!
Have a look at std::thread for basic threading in general. In case of an int depending on the platform, it might simply work. If you want to be sure, use an std::atomic<int>
std::atomic<int> global_value;
void task() {
while(true) {
...//calculate value(value will change every loop)
global_value.store(value);
}
}
int main() {
...
while(true) {
int v = global_value.load();
....
}
}
std::atomic<int> will make sure, that all read and write accesses are atomic.
Make the variable outside main, and above functions.
One thing you could additionally do, is make your function recursive. Then set it up in a <thread>, which if you haven't already included, then you're not close to done. A thread is a separate routine running the whole time your other tasks are running. A recursive function is one that calls itself unless one base case is reached. Then it returns. So we need to change your thread's variable, which you can do easily just by following what I said above. Thread instructions at cplusplus.com will help you more. So do try and research it. It's out there. And if you want top level help, there's books as well. You need to have the reading skills to look at code the right way. And the only way you'll learn independence is to stalk the information down and learn it. It's old school, but it'll always work.
std::thread first (task,arg);
That instances your thread, and you've called it first. So all methods are going to be referenced through first. like first.join() which will meet you back up with the thread, after you've first.detach() from it. In the case you do, you have to .join() again to destroy it. Much like a pointer. It has become independent of the program at that point, and is running in the background.
If you want to destroy it
first.~thread();
For purposes of thread local cleanup I need to create an assertion that checks if the current thread was created via boost::thread. How can I can check if this was the case? That is, how can I check if the current thread is handled by boost::thread?
I simply need this to do a cleanup of thread local storage when the thread exits. Boost's thread_local_ptr appears to only work if the thread itself is a boost thread.
Note that I'm not doing the check at cleanup time, but sometime during the life of the thread. Some function calls one of our API/callbacks (indirectly) causing me to allocate thread-local storage. Only boost threads are allowed to do this, so I need to detect at that moment if the thread is not a boost thread.
Refer to Destruction of static class members in Thread local storage for the problem of not having a generic cleanup handler. I answered that and realized pthread_clenaup_push won't actually work: it isn't called on a clean exit form the thread.
While I don't have answer to detect a boost thread the chosen answer does solve the root of my problem. Boost thread_specific_ptr's will call their cleanup in any pthread. It must have been something else causing it not to work for me, as an isolated test shows that it does work.
The premise for your question is mistaken :) boost::thread_specific_ptr works even if the thread is not a boost thread. Think about it -- how would thread specific storage for the main thread work, seeing as it's impossible for it to be created by boost? I have used boost::thread_specific_ptr from the main thread fine, and although I haven't examined boost::thread_specific_ptr's implementation, the most obvious way of implementing it would work even for non-boost threads. Most operating systems let you get a unique ID number for the current thread, which you can then use as an index into a map/array/hashtable.
More likely you have a different bug that prevents the behavior you're expecting to see from happening. You should open a separate question with a small compilable code sample illustrating the unexpected behavior.
You can't do this with a static assertion: That would mean you could detect it at compile time, and that's impossible.
Assuming you mean a runtime check though:
If you don't mix boost::thread with other methods, then the problem just goes away. Any libraries that are creating threads should already be dealing with their own threads automatically (or per a shutdown function the API documents that you must call).
Otherwise you can keep, for example, a container of all pthread_ts you create not using boost::thread and check if the thread is in the container when shutting down. If it's not in the container then it was created using boost::thread.
EDIT: Instead of trying to detect if it was created with boost::thread, have you considered setting up your application so that the API callback can only occur in threads created with boost::thread? This way you prevent the problem up front and eliminate the need for a check that, if it even exists, would be painful to implement.
Each time a boost thread ends, all the Thread Specific Data gets cleaned. TSD is a pointer, calling delete p* at destruction/reset.
Optionally, instead of delete p*, a cleanup handler can get called for each item. That handler is specified on the TLS constructor, and you can use the cleanup function to do the one time cleaning.
#include <iostream>
#include <boost/thread/thread.hpp>
#include <boost/thread/tss.hpp>
void cleanup(int* _ignored) {
std::cout << "TLS cleanup" << std::endl;
}
void thread_func() {
boost::thread_specific_ptr<int> x(cleanup);
x.reset((int*)1); // Force cleanup to be called on this thread
std::cout << "Thread begin" << std::endl;
}
int main(int argc, char** argv) {
boost::thread::thread t(thread_func);
t.join();
return 0;
}
I am looking for the best way to solve the following (c++) problem. I have a function given by some framework, which returns an object. Sometimes it takes just miliseconds, but on some occasions it takes minutes. So i want to stop the execution if it takes longer than let's say 2 seconds.
I was thinking about doing it with boost threads. Important sidenote, if the function returns faster than the 2 seconds the program should not wait.
So i was thinking about 2 threads:
1.thread: execute function a
2.thread: run timer
if(thread 2 exited bevore thread 1) kill thread 1
else do nothing
I am struggeling a bit the practical implementation. Especially,
how do i return an object from a child boost thread to the main thread?
how do i kill a thread in boost?
is my idea even a good one, is there a better way to solve the problem in c++ (with or without boost)?
As for waiting, just use thread::timed_join() inside your main thread, this will return false, if the thread didn't complete within the given time.
Killing the thread is not feasible if your third-party library is not aware of boost:threads. Also, you almost certainly don't want to 'kill' the thread without giving the function the possibility to clean up.
I'd suggest that you wait for, say, 2 seconds and then continue with some kind of error message, letting the framework function finish its work and just ignoring the result if it came too late.
As for returning a value, I'd suggest something like
struct myfunction {
MyObj returnValue;
void operator() () {
// ...
returnValue = theComputedReturnValue;
}
};
// ...
myfunction f;
boost::thread t = boost::thread(boost::ref(f));
t.join(); // or t.timed_join()...
use(f.returnValue);
// ...
I have done something similar by the past and that works (even though not ideal).
To get the return value just "share" a variable (that could be just a pointer (initially nil) to the returned value, or a full object with a state etc ...) and make your thread read/udate it. Don't forget to mutex it needed. That should be quite straight forward.
Expanding what James has said above, "kill a thread" is such a harsh term! :) But interruption is not so easy either, typically with boost threads, there needs to be an interruption point, where the running thread can be interrupted. There is a set of these interruptible functions (unfortunately they are boost specific), such as wait/sleep etc. One option you have is in the first thread, liberally scatter interruption_points(). Such that when you call interrupt() once thread 2 dies, at the next interruption_point() thread 1 will throw an exception.
Threads are in the same process space, thus you can have shared state between multiple threads as long as there is synchronized access to that shared state.
EDIT: just noticed that the OP has already looked into this... will leave the answer up anyway I guess...
Is the following safe?
I am new to threading and I want to delegate a time consuming process to a separate thread in my C++ program.
Using the boost libraries I have written code something like this:
thrd = new boost::thread(boost::bind(&myclass::mymethod, this, &finished_flag);
Where finished_flag is a boolean member of my class. When the thread is finished it sets the value and the main loop of my program checks for a change in that value.
I assume that this is okay because I only ever start one thread, and that thread is the only thing that changes the value (except for when it is initialised before I start the thread)
So is this okay, or am I missing something, and need to use locks and mutexes, etc
You never mentioned the type of finished_flag...
If it's a straight bool, then it might work, but it's certainly bad practice, for several reasons. First, some compilers will cache the reads of the finished_flag variable, since the compiler doesn't always pick up the fact that it's being written to by another thread. You can get around this by declaring the bool volatile, but that's taking us in the wrong direction. Even if reads and writes are happening as you'd expect, there's nothing to stop the OS scheduler from interleaving the two threads half way through a read / write. That might not be such a problem here where you have one read and one write op in separate threads, but it's a good idea to start as you mean to carry on.
If, on the other hand it's a thread-safe type, like a CEvent in MFC (or equivilent in boost) then you should be fine. This is the best approach: use thread-safe synchronization objects for inter-thread communication, even for simple flags.
Instead of using a member variable to signal that the thread is done, why not use a condition? You are already are using the boost libraries, and condition is part of the thread library.
Check it out. It allows the worker thread to 'signal' that is has finished, and the main thread can check during execution if the condition has been signaled and then do whatever it needs to do with the completed work. There are examples in the link.
As a general case I would neve make the assumption that a resource will only be modified by the thread. You might know what it is for, however someone else might not - causing no ends of grief as the main thread thinks that the work is done and tries to access data that is not correct! It might even delete it while the worker thread is still using it, and causing the app to crash. Using a condition will help this.
Looking at the thread documentation, you could also call thread.timed_join in the main thread. timed_join will wait for a specified amount for the thread to 'join' (join means that the thread has finsihed)
I don't mean to be presumptive, but it seems like the purpose of your finished_flag variable is to pause the main thread (at some point) until the thread thrd has completed.
The easiest way to do this is to use boost::thread::join
// launch the thread...
thrd = new boost::thread(boost::bind(&myclass::mymethod, this, &finished_flag);
// ... do other things maybe ...
// wait for the thread to complete
thrd.join();
If you really want to get into the details of communication between threads via shared memory, even declaring a variable volatile won't be enough, even if the compiler does use appropriate access semantics to ensure that it won't get a stale version of data after checking the flag. The CPU can issue reads and writes out of order as long (x86 usually doesn't, but PPC definitely does) and there is nothing in C++9x that allows the compiler to generate code to order memory accesses appropriately.
Herb Sutter's Effective Concurrency series has an extremely in depth look at how the C++ world intersects the multicore/multiprocessor world.
Having the thread set a flag (or signal an event) before it exits is a race condition. The thread has not necessarily returned to the OS yet, and may still be executing.
For example, consider a program that loads a dynamic library (pseudocode):
lib = loadLibrary("someLibrary");
fun = getFunction("someFunction");
fun();
unloadLibrary(lib);
And let's suppose that this library uses your thread:
void someFunction() {
volatile bool finished_flag = false;
thrd = new boost::thread(boost::bind(&myclass::mymethod, this, &finished_flag);
while(!finished_flag) { // ignore the polling loop, it's besides the point
sleep();
}
delete thrd;
}
void myclass::mymethod() {
// do stuff
finished_flag = true;
}
When myclass::mymethod() sets finished_flag to true, myclass::mymethod() hasn't returned yet. At the very least, it still has to execute a "return" instruction of some sort (if not much more: destructors, exception handler management, etc.). If the thread executing myclass::mymethod() gets pre-empted before that point, someFunction() will return to the calling program, and the calling program will unload the library. When the thread executing myclass::mymethod() gets scheduled to run again, the address containing the "return" instruction is no longer valid, and the program crashes.
The solution would be for someFunction() to call thrd->join() before returning. This would ensure that the thread has returned to the OS and is no longer executing.