Original Post
Hi,
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
#include
#include
#include
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 vthreads;
for(int i=1; i<=N_Threads; i++)
vthreads.push_back(thread(hello));
for(auto &thread : vthreads)
thread.join();
return 0;
}
[/source]
[color=#ff0000]EDIT: I don't see the source code in my pc. I'm going to paste it here:
[color=#ff0000]#include
#include
#include
#include
[color=#ff0000]using namespace std;
[color=#ff0000]void hello()
{
mutex m;
m.lock();
cout << "I'm a thread" << endl;
m.unlock();
}
[color=#ff0000]const int N_Threads = 5;
[color=#ff0000]int main()
{
vector vthreads;
for(int i=1; i<=N_Threads; i++)
vthreads.push_back(thread(hello));
for(auto &thread : vthreads)
thread.join();
return 0;
[color=#ff0000]}
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.
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
#include
#include
#include
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
for(int i=1; i<=N_Threads; i++)
vthreads.push_back(thread(hello));
for(auto &thread : vthreads)
thread.join();
return 0;
}
[/source]
[color=#ff0000]EDIT: I don't see the source code in my pc. I'm going to paste it here:
[color=#ff0000]#include
#include
#include
#include
[color=#ff0000]using namespace std;
[color=#ff0000]void hello()
{
mutex m;
m.lock();
cout << "I'm a thread" << endl;
m.unlock();
}
[color=#ff0000]const int N_Threads = 5;
[color=#ff0000]int main()
{
vector
for(int i=1; i<=N_Threads; i++)
vthreads.push_back(thread(hello));
for(auto &thread : vthreads)
thread.join();
return 0;
[color=#ff0000]}
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.