I'm using the new threads features that C++11 provides, but it isn't working as i'd expect. I wonder if this trouble is because i'm doing something wrong or because c++11 still lacks of maturity.
The code:
[source lang="cpp"]#include <thread>#include <mutex>#include <iostream>#include <vector>using namespace std;void hello(){ mutex m; m.lock(); cout << "I'm a thread" << endl; m.unlock();}const int N_Threads = 5;int main(){ vector<thread> vthreads; for(int i=1; i<=N_Threads; i++) vthreads.push_back(thread(hello)); for(auto &thread : vthreads) thread.join(); return 0;}[/source]
EDIT: I don't see the source code in my pc. I'm going to paste it here:
#include <thread>
#include <mutex>
#include <iostream>
#include <vector>
using namespace std;
void hello()
{
mutex m;
m.lock();
cout << "I'm a thread" << endl;
m.unlock();
}
const int N_Threads = 5;
int main()
{
vector<thread> vthreads;
for(int i=1; i<=N_Threads; i++)
vthreads.push_back(thread(hello));
for(auto &thread : vthreads)
thread.join();
return 0;
}
Below this, an example of the program output:
I'm a threadI'm a thread
I'm a thread
I'm a thread
I'm a thread
In a first instance, I simply ran the program without using mutexes and displayed a very similar previous output. In that moment, I supposed the "cout" object (in addition with the "<<" message) wasn't thread safe, so I put the mutex to try to prevent the interleaving, but it seems it didn't work.
What's happening?
Thank you.
Edited by nimrodson, 24 July 2012 - 09:18 PM.






