Answer the question
In order to leave comments, you need to log in
How to use shared variables in multithreaded c++ programs?
Hello.
I wanted to check how multithreading works in c++, but with the code below I always get "safe_mode: FALSE"
The idea of what I want to do is to take sensor readings at a higher speed (while loop) in several parallel processes, but write them to the general variables , which is read by the main function (also while loop) and behaves differently depending on the values of common variables. What is the best way to implement this?
#include <thread>
#include <iostream>
using namespace std;
bool safe_mode = true;
bool *pnt_safe_mode = &safe_mode;
void stupidFunc() {
int i = 0;
while (i <= 10000)
{
if (*pnt_safe_mode == true)
{
*pnt_safe_mode = false;
}
else {
*pnt_safe_mode = true;
}
i++;
}
}
int main()
{
std::thread t(stupidFunc);
t.detach();
for (int i = 0; i <= 10000; i++) {
if (*pnt_safe_mode) {
cout << "safe_mode: TRUE\n";
}
else {
cout << "safe_mode: FALSE\n";
}
}
system("pause");
return 0;
}
Answer the question
In order to leave comments, you need to log in
For simple data types, you can use std::atomic
For example, for your program
std::atomic<bool> safe_mode = true;
void stupidFunc() {
int i = 0;
while (i <= 10000)
{
if (safe_mode == true)
{
safe_mode = false;
}
else {
safe_mode = true;
}
i++;
}
}
int main()
{
std::thread t(stupidFunc);
t.detach();
for (int i = 0; i <= 10000; i++) {
if (safe_mode) {
cout << "safe_mode: TRUE\n";
}
else {
cout << "safe_mode: FALSE\n";
}
}
system("pause");
return 0;
}
how does multithreading work in c++
Well, let's start with the fact that 10000 iterations on a modern processor will be executed so quickly that it will probably fit into the time quantum allotted to the thread, and the second thread will most likely not even have time to get processor time to change your variable. Therefore, EXCLUSIVELY for the purposes of experiment, you can try to increase the number of iterations to at least 10 million, and turn off optimizations as much as possible (not because of speed, but because of the potential throwing of the code by the compiler), because surely the number of iterations is the reason for the failure in your experiment.
But seriously, you have already been given advice on what to do - without normal synchronization in a multi-threaded environment, you cannot give any common variables of results. If you really don’t want to take a mutex (although in order not to take it, you need to clearly know that it is not suitable), you can turn your common flag into a spinlock, but you won’t get off with code on the pluses.
From an architectural point of view, if you have readings, then you just have a classic producer-consumer case - insert a thread-safe queue, and use it.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question