How to sync "for" loop counter on multithread?
If these multi thread program
void Func(int n){
for(int i=0; i<n; i++){ //at the same time with other Func()
cout << i <<endl;
}
}
void main(){
std::thread t1(Func(2));
std::thread t2(Func(2));
t1.join();
t2.join();
}
When executing Func() in parallel , I want to sync "for" loop counter "i".
For example, the program has possibility to output the result
0
1
0
1
but I want to always get the result
0
0
1
1
Can I it?
One way to do it would be to use a few variables for the threads to coordinate things (in the following they are globals, just for simplicity).
The
index
variable says at which index are the threads, and thecount
variable says how many threads are at the index still.Now you're loop becomes:
Here is the full code: