Skip to content

Instantly share code, notes, and snippets.

@mosfet1kg
Created July 3, 2015 02:40
Show Gist options
  • Save mosfet1kg/dfdf30f4f1d35ca6fb0f to your computer and use it in GitHub Desktop.
Save mosfet1kg/dfdf30f4f1d35ca6fb0f to your computer and use it in GitHub Desktop.
thread race condition
#include <semaphore.h>
#include <stdio.h>
#include <errno.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/mman.h>
#define MAX_SIZE 32
typedef enum {false, true} bool;
//gcc -o main main.c -lpthread
volatile int cnt = 0; /* global */
sem_t empty, mutex, full;
void *fun_thread1(void *tmp);
void *fun_thread2(void *tmp);
int main(int argc, char **argv)
{
int tmp = 0;
/* 세마포어를 생성화고 초기화 한다. */
if( sem_init(&mutex, 0, 1) < 0) {
perror("mutex: semaphore initilization");
exit(0);
}
if( sem_init(&full, 0, 0) < 0 ){
perror("full: semaphore initilization");
exit(0);
}
if( sem_init(&empty, 0, MAX_SIZE) < 0 ){
perror("full: semaphore initilization");
exit(0);
}
pthread_t tid_1, tid_2;
pthread_create(&tid_1, NULL, fun_thread1, &tmp);
pthread_create(&tid_2, NULL, fun_thread2, &tmp);
pthread_join( tid_1, NULL);
pthread_join( tid_2, NULL);
printf("=======%d\n", cnt);
return 0;
}
void *fun_thread1(void *tmp){
int i;
for(i=0; i<10000000; i++){
sem_wait(&mutex);
cnt++;
sem_post(&mutex);
}
}
void *fun_thread2(void *tmp){
int i;
for(i=0; i<10000000; i++){
sem_wait(&mutex);
cnt++;
sem_post(&mutex);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment