Reputation: 23
I am learning multithreading in C++ in which I wrote a simple program where multiple threads call the same function . At each function call, I am passing different argument values.
Below is the program with output snippet.
void add(int x,int y) {
int sum = x + y;
cout<<sum<<endl;
}
int main()
{
int a,b;
vector<thread> th;
for(int i=0;i<100;i++) {
a=i;
b=i+1;
th.push_back(thread(add,a,b));
}
for(int i=0;i<100;i++)
th[i].join();
}
Maximum sum should be 201 but in output but one entry is showing 713. This might be as threads run independently and so the results are random. Output :
31
19
11
713
9
5
21
...
I want to know that how can I obtain its output in sequence.
As each thread creates its own call stack and local function variables for the same function called by different threads are unique, so, I think in this case mutex lock is not required as each thread is executing the code in its own address space, they are not sharing any variable. Please correct me if I am wrong?
Also, please suggest some resources (ebooks, courses etc.) to learn basics of multithreading in C++.
Upvotes: 1
Views: 1452
Reputation: 38751
713 is 7 and 13. Try
void add(int x,int y) {
int sum = x + y;
cout<< std::to_string(sum) + "\n";
}
You should use a mutex to exclusively access std::cout.
Upvotes: 1