Last active
April 5, 2021 14:38
-
-
Save ccckmit/1b297cbd3bb0fc068d80c8696454c79d to your computer and use it in GitHub Desktop.
Revisions
-
ccckmit revised this gist
May 31, 2018 . 1 changed file with 2 additions and 2 deletions.There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -26,9 +26,9 @@ void *dec() int main() { pthread_t thread1, thread2; pthread_create(&thread1, NULL, inc, NULL); pthread_create(&thread2, NULL, dec, NULL); pthread_join( thread1, NULL); -
ccckmit created this gist
May 31, 2018 .There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal 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); }