Skip to content

Instantly share code, notes, and snippets.

@ccckmit
Last active April 5, 2021 14:38
Show Gist options
  • Save ccckmit/1b297cbd3bb0fc068d80c8696454c79d to your computer and use it in GitHub Desktop.
Save ccckmit/1b297cbd3bb0fc068d80c8696454c79d to your computer and use it in GitHub Desktop.
#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);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment