[Omp] Shared Variable Problem
Yuan Lin
Yuan.Lin at Sun.COM
Fri Jul 28 19:32:48 PDT 2006
The value of a shared variable updated by one thread is not guaranteed
to be seen by another thread unless flush (implicit or explicit) is
used. The memory model is described in Spec 2.5. In your sample, the
value of i may always be read from a register.
Try the following code and see if it works as you wanted.
i = 0;
#pragma omp parallel private(tid)
{
tid = omp_get_thread_num();
while(1)
{
if (!tid)
{
#pragma omp flush(i)
printf("master: i = %d\n", i);
fflush(stdout);
}
else
{
printf("worker: i = %d\n", i);
fflush(stdout);
i ++;
#pragma omp flush(i)
}
}
}
Also depending on how the threads are scheduled, you may see thousands
of master: i=0 before you see worker: i=1, 2, 3, ...., then you may see
master: i= some big number. Do not expect to see the value of i printed
from the master be to consecutive. There is no synchronization between
the master thread and the slave thread in your code.
Hope it helps.
-- Yuan
----------------------------------------
http://blogs.sun.com/roller/page/yuanlin
----------------------------------------
KaveH Aasaraai wrote:
> Hey guys,
>
> I'm new to this OpenMP thing. I'm facing this problem
> of using a shared value, and trying to synchronize two
> threads with this shared variable. Any help would
> really be appreciated. Here is the problem:
>
> i = 0;
>
> #pragma omp parallel private(tid)
> tid = omp_get_thread_num();
> while(1)
> {
> if (!tid)
> {
> printf("master: i = %d\n", i);
> fflush(stdout);
> }
> else
> {
> printf("worker: i = %d\n", i);
> fflush(stdout);
> i ++;
> }
> }
>
> The "0" thread doesn't see the changes to the shared
> variable, i. If I remove the while(1) thing, then the
> value printed for "i" is correct. Here is a sample
> (partial) output:
>
>
> master: i = 0
> master: i = 0
> master: i = 0
> worker: i = 2445
> worker: i = 2446
> worker: i = 2447
> worker: i = 2448
> worker: i = 2449
> worker: i = 2450
> worker: i = 2451
> worker: i = 2452
>
>
>
> Thanks to you guys in advance,
>
> Kaveh
>
> __________________________________________________
> Do You Yahoo!?
> Tired of spam? Yahoo! Mail has the best spam protection around
> http://mail.yahoo.com
> _______________________________________________
> Omp mailing list
> Omp at openmp.org
> http://openmp.org/mailman/listinfo/omp
More information about the Omp
mailing list