I'm recent to learning threads and there's a thought that I have in my mind. Let's say I have the following code:
#include <iostream>
#include <thread>
#include <mutex>
using namespace std;
int myAmount = 0;
std::mutex m;
void addMoney(){
m.lock();
myAmount++;
m.unlock();
}
int main(){
thread t1(addMoney);
thread t2(addMoney);
t1.join();
t2.join();
cout<<addMoney<<endl;
return 0;
}
Here mutex prevents the race condition by locking the thread application until it gets finished. Till the thread is working, another thread t2 is kept in a queue. Once thread t1 is finished, the variable in the data segment of the memory gets updated and the queue passes on permitting thread t2 to work. We know we use threads for parallel processing, but here the processing of the threads is sequential rather than parallel. So if I write a single thread version of the above code, which would run faster? The multi-threaded one or the single-threaded one?
Please correct me where I'm wrong about the concept.