开发者

Whats going wrong with my code ? The global variable value changed while using semaphore

          #include<pthread.h>
          #include<stdio.h>
          #include<semaphore.h>
              void func();
              int a;
              int main()
              {  

                 pthread_t thread1;
                 sem_t semaphore1;
                 sem_init(&semaphore1,0,1);
                 pthread_create(&thread1,NULL,(void *)func,NULL);
                 sem_wait (&semaphore1);
                 a=62;
                 printf("%d",a); \\ as i found on google 
                 sleep(2);   \\ i believe a value should be sticked to 62
                 sleep(1);    \\ but output shows different why?
                 printf("%d",a);
                 sem_post(&semaphore1);
              } 
            void func()
             {  
              a=45;
              sleep(1);
              a=32;
              a=开发者_JAVA技巧75;
           printf("hello");
             }

When i Googled it.I found sem_wait locks the global variable so that no other thread access the variable.

But when i tried these code the output is

           62 
           hello 
           75.

The a value got changed but note that the printf("%d",a) is under the sem_wait ,Whats wrong with my code?


Semaphores offer only advisory locking. They don't know about variables and such, they lock regions of your code. They don't enforce anything so you must call wait and post yourself.

Here is what wait and post really mean when used in your example.

sem_wait (&semaphore1); /* AKA "may I enter this region" */

sem_post(&semaphore1); /* AKA "I am done with this region. */

The way I see it, main asks for permission before entering. func doesn't ask for permission before modifying a.

So func should wait and post.

void func()
{
    sem_wait (&semaphore1);
    a=45;
    sleep(1);
    a=32;
    a=75;
    printf("hello");
    sem_post (&semaphore1);
}

Of course, for this sempahore1 should be globally accessible.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜