I am quite new to c++ and to threading, so this quesiton may be stupid. However, I have found preciously little information about my problem though I have searched for a solution for a long time. The problem is that I am unable to change the value of a variable outside its thread. The code snippet that I provide is shortened down to a reasonable size, but my issue should not have been affected.
I have done many different actions trying to slove the problem, but it still persists. The problem is that when I change the variables from
, is_input
and dummy
inside f
they are not changed in the main thread. I am not sure, but I doubt that it has something to do with other actions happen while the thread is Writing. It must be something that I miss here. I would be thankful for all input that helps solving the problem.
By the way, I am aware this may be something that I am meant to learn after getting a Little more used to the language, but many thing that is fun or motivating to program is possible after learning about threads.
#include<vector>
#include<string>
#include<iostream>
#include<mutex>
#include<chrono>
#include<thread>
std::mutex m;
void f(std::string& from, bool& is_input, int& dummy){
if (is_input == false){
std::cout<<"From"<<"\n";
std::cin>> from;
std::unique_lock<std::mutex> lck(m);
is_input = true;
std::cout<<"is_input: "<<is_input<<" from "<<from<<std::endl;
//lck.unlock(); //Should not be needed
}
++dummy;
std::cout<<"dummy: "<<dummy<<std::endl;
}
int main(){
std::string from = "";
bool is_input = false;
using namespace std::chrono;
int counter = 0;
int dummy = 1;
std::thread th1(f,from, is_input, dummy);
th1.join();
while (1)
{
++counter;
std::this_thread::sleep_for(milliseconds(4000));
std::cout<<"the thread have slept now, prints is_input and dummy\n"<<is_input<<" "<<dummy<<std::endl;
if (counter == 2){
break;
}
}
system("PAUSE");
}