Skip to main content
GameDev.net gamedev.net
🔒 Locked

thread issue in c++11

Started by nimrodson Jul 25, 2012 at 3:06 AM 1 replies 2.1k views
Original Post
nimrodson
nimrodson
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.
juggler
juggler
The mutex must be shared between the threads, so move the mutex declaration out of the hello function and make it global instead. At the moment each thread has its own mutex, so locking it does nothing.
nimrodson
nimrodson

The mutex must be shared between the threads, so move the mutex declaration out of the hello function and make it global instead. At the moment each thread has its own mutex, so locking it does nothing.


You're right, what stupid mistake I made! I need more reading on concurrency topics.
Thank you very much!

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.