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();
Related
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.
I have this line of code in my main() method of my C++ method:
std::thread foo (bar);
That works fine. However, I would like to run this same thread any time that I want to based on external input. How can I re-use this thread to run the thread again?
The reason I'm doing this is I have two functions that need to be ran at the same time: one that is blocking and takes an input, x, and outputs the data to the output at set intervals. The other one is blocking and produces an output, y, based on external input. This is basically what it should look like:
int shared_x = 0;
int producer_x = 0;
int consumer_x = 0;
std::thread producer (foo); //Modifies foo_x
std::thread consumer (bar); //Outputs based on foo2_x
while( ;; ) {
if(producer .join()) {
shared_x = producer_x;
//How should I restart the thread here?
}
if(consumer.join()) {
consumer_x = shared_x;
//Here too?
}
}
That seems to handle the whole thread safety issue and allow them both to safely operate at the same time with little time waiting. The only issue is I don't know how to restart the thread. How do I do this?
Reading through some documentation, I found this works:
myOldThread = thread(foobar);
I assume there's still quite a bit of performance overhead, but at least I can reuse the same variable. :/
An alternative approach would be to never let the thread die (have a loop with a 200ms delay that checks a mutex-protected boolean for when it should run again). Not super clean, but if performance matters, this is probably the best way to do this.
Boost::ThreadPool could also be a good option. By using that you can pick threads from pool to assign tasks.
How to create a thread pool using boost in C++?
Suppose an object X is supposed to run forever. X is running threads with infinite loops inside, so the program will never exit.
My question is this: is it a good practice to put use the join() method at all, for example, in the deconstructor, or would it make more sense to do something like
int main() {
X myX;
while(1) {
}
return 0;
}
Are there any differences between the two approaches?
Sometimes it is required, often it is not. If you can design your app so that it does not, so much the better.
You would want to call join() if some part of your program needed to wait to run until a thread exited. It also makes the thread object destroyable so you don't create a memory leak. Threads that haven't been joined are like zombie processes and waste resources.
The naming of this function seems like this is some complicated stuff going on. When exactly does one know that this is the way to go instead of doing something like this:
Preparation
CRITICAL_SECTION cs;
int *p = malloc(sizeof(int)); // Allocation Site
InitializeCriticalSection(&cs); // HINT for first Write
Thread #1
{
*p = 1; // First Write
}
Thread #2
{
EnterCriticalSection(&cs);
*p = 2; // Second Write
LeaveCriticalSection(&cs);
}
I have a write that gets done in one thread:
Run()
{
// some code
m_bIsTerminated = TRUE;
// some more code
}
Then, I have a read that gets done in another thread (potentially at the same time):
Terminate()
{
// some code
if( m_bIsTerminated )
{
m_dwThreadId = 0;
m_hThread = NULL;
m_evExit.SetEvent();
return;
}
// even more code
}
What's the best solution to solve this race condition? Are critical sections the way to go or is the use of InterlockedExchangeAdd() more useful?
In your case, there's no race condition. The variable is never reset back to FALSE, is it? It's just a "please die" switch for the thread, right? Then no need for synchronization of any kind.
The InterlockedXXX family of functions makes use of Intel CPU's atomic 3-operand commands (XADD and CMPXCNG). So they're much cheaper than a critical section. And the one you want for thread-safe assignment is InterlockedCompareExchange().
UPD: and the mark the variable as volatile.
InterlockedExchangeAdd is used to add a value to an integer as an atomic operation, meaning that you won't have to use a critical section. This also removes the risk of a deadlock if one of your threads throws an exception - you need to make sure that you don't keep any lock of any kind as that would prevent other threads from acquiring that lock.
For your scenario you can definitely use an Interlocked...- function, but I would use an event (CreateEvent, SetEvent, WaitForSingleObject), probably because I often find myself needing to wait for more than one object (you can wait for zero seconds in your scenario).
Upd: Using volatile for the variable may work, however it isn't recommended, see: http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2006/n2016.html and http://www-949.ibm.com/software/rational/cafe/blogs/ccpp-parallel-multicore/tags/c%2B%2B0x for instance.
If you want to be portable, take a look at boost::thread.
Make sure m_bIsTerminated is marked as volatile, and you should be ok. Although it seems pretty weird to me that you'd // some more code after setting "is terminated" to true. What exactly does that variable indicate?
Your "race condition" is that your various elements of // more code can execute in different orders. Your variable doesn't help that. Is your goal to get them to execute in a deterministic order? If yes, you'd need a condition variable to wait on one thread and set in another. If you just don't want them executing concurrently, a critical section would be fine.
I'm making a dll that has to respond to an application's requests. One of the application's requirements is that a call should not take long to complete.
Say, I have a function foo(), which is called by the host application:
int foo(arg){
// some code i need to execute, say,
LengthyRoutine();
return 0;
}
Lets say, foo has to perform a task (or call a function) that is certain to take a long time. The application allows me to set a wait variable; if this variable is non-zero when foo returns, it calls foo again and again (resetting the wait variable before each call) until wait is returned 0.
What's the best approach to this?
Do I go:
int foo(arg){
if (inRoutine == TRUE) {
wait = 1;
return 0;
} else {
if (doRoutine == TRUE) {
LengthyRoutine();
return 0;
}
}
return 0;
}
This doesn't really solve the problem that LengthyRoutine is gonna take a long time to complete. Should I spawn a thread of some sort that updates inRoutine depending on whether or not it has finished its task?
Thanks..
Spawning another thread is pretty much the best way to do it, just make sure you set the result variables before you set the variable that says you're finished to avoid race conditions. If this is called often you might want to spawn a worker thread ahead of time and reuse it to avoid thread start overhead.
There is another possible solution, do part of the work each time the function is called, however this spends more time in the DLL and probably isn't optimal, as well as being more complex to implement the worker code for most algos.
If C programming, use callback - pass the callback to foo. You have to agree on the callback signature and do some housekeeping to trigger it when the work in LengthyRoutine is done.
typedef (void) callbackFunction(void);
int foo(arg, callbackFunction)
{
// some code i need to execute, say,
// register callback and return right away
// Trigger the LengthyRoutine to run after this function returns
return 0;
}
LengthyRoutine()
{
// do lenghty routine
// now inform the caller with their suppiled callback
callbackFunction();
}
Essentially Observer Pattern in C. C++ makes the work a lot easier/cleaner in my opinion
If incredible rare situation where LengthyRoutine() isn't 3rd party code and you have all the source and it's possible to split it up then you can consider using coroutines.