I figure out what the problem was.
I have a variable which I use to assign each thread with a unique number
When I assign each thread in the thread function I use pthread_mutex_lock to ensure that only one thread can write to the variable:
Example
1 2 3 4 5 6
|
void worker(void)
{
pthread_mutex_lock(&m_mutex);
unsigned int id = running_threads++;
pthread_mutex_unlock(&m_mutex);
}
|
running_threads
is a global variable and is set to zero at the start. When I call
pthread_create()
I can measure on it to ensure that all threads have got their ids before I move on in the program.
In my
init() function I only read
running_threads
, so in theory I do not need to lock/unlock m_mutex before I read it.
Example. I start 8 threads. So
n_threads = 8
, where n_threads is a global variable as running_threads also is.
I put these two variables into a while loop as a kind of barrier, to measure if all threads got their ids
1 2
|
// wait to all threads got their ids
while(running_threads < n_threads) continue;
|
This works fine, when you use no optimization flags (-O0).
When you use -O1 or -O2 it seems the while loop got its own scope where it keeps the information for running_threads and n_threads.
So even though I print this out on the screen, the while loop goes into a infinity loop:
1 2 3 4
|
while(running_threads < n_threads)
{
std::cout << "running_threads=" << running_threads << ", n_threads=" << n_threads << std::endl;
}
|
The output is:
running_threads=0, n_threads=8
running_threads=2, n_threads=8
running_threads=5, n_threads=8
running_threads=8, n_threads=8
running_threads=8, n_threads=8
running_threads=8, n_threads=8
running_threads=8, n_threads=8
running_threads=8, n_threads=8
running_threads=8, n_threads=8
....
|
When i declare running_threads with the volatile keyword, it works with -O1 and -O2
|
volatile unsigned int running_threads = 0;
|
If you think another solution would be better than this one, I will be glad if you write some words. Or else I use this solution.
Maybe I could have used pthread_barrier instead...
/Jesper