Skip to content

Instantly share code, notes, and snippets.

@ccckmit
Last active April 5, 2021 14:38
Show Gist options
  • Select an option

  • Save ccckmit/1b297cbd3bb0fc068d80c8696454c79d to your computer and use it in GitHub Desktop.

Select an option

Save ccckmit/1b297cbd3bb0fc068d80c8696454c79d to your computer and use it in GitHub Desktop.

Revisions

  1. ccckmit revised this gist May 31, 2018. 1 changed file with 2 additions and 2 deletions.
    4 changes: 2 additions & 2 deletions norace.c
    Original file line number Diff line number Diff line change
    @@ -26,9 +26,9 @@ void *dec()

    int main()
    {
    pthread_t thread1, thread2;
    pthread_t thread1, thread2;

    pthread_create(&thread1, NULL, inc, NULL);
    pthread_create(&thread1, NULL, inc, NULL);
    pthread_create(&thread2, NULL, dec, NULL);

    pthread_join( thread1, NULL);
  2. ccckmit created this gist May 31, 2018.
    37 changes: 37 additions & 0 deletions norace.c
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,37 @@
    #include <stdio.h>
    #include <pthread.h>

    pthread_mutex_t mutex1 = PTHREAD_MUTEX_INITIALIZER;
    #define LOOPS 100000
    int counter = 0;

    void *inc()
    {
    for (int i=0; i<LOOPS; i++) {
    pthread_mutex_lock( &mutex1 ); // 上鎖、避免競爭情況
    counter = counter + 1; // 臨界區間、修改共用變數中
    pthread_mutex_unlock( &mutex1 ); // 變數修改完畢,解鎖
    }
    }

    void *dec()
    {
    for (int i=0; i<LOOPS; i++) {
    pthread_mutex_lock( &mutex1 ); // 上鎖、避免競爭情況
    counter = counter - 1; // 臨界區間、修改共用變數中
    pthread_mutex_unlock( &mutex1 ); // 變數修改完畢,解鎖
    }
    }


    int main()
    {
    pthread_t thread1, thread2;

    pthread_create(&thread1, NULL, inc, NULL);
    pthread_create(&thread2, NULL, dec, NULL);

    pthread_join( thread1, NULL);
    pthread_join( thread2, NULL);
    printf("counter=%d\n", counter);
    }