Skip to content
Snippets Groups Projects
Commit df17afeb authored by 희원 전's avatar 희원 전
Browse files

Upload New File

parent 478df87e
Branches
No related tags found
No related merge requests found
syncrw.c 0 → 100644
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <stdbool.h>
#include <pthread.h>
#include <semaphore.h>
#define THREAD_SIZE 3
#define ITER_PER_THREAD 4
void *reader(void *arg);
void *writer(void *arg);
int num = 0;
sem_t mutex;
int main(void)
{
pthread_t w[THREAD_SIZE];
pthread_t r[THREAD_SIZE];
sem_init(&mutex, 0, 1);
printf("Start program\n\n");
for(int i = 0; i < 3; i++){
int w_thread = pthread_create(&w[i], NULL, (void *)writer, (void*)&i);
if(w_thread < 0){
perror("thread create error : ");
exit(0);
}
int r_thread = pthread_create(&r[i], NULL, (void *)reader, (void*)&i);
if(r_thread < 0){
perror("thread create error : ");
exit(0);
}
}
for(int i = 0; i < 3; i++)
{
pthread_join(w[i],NULL);
pthread_join(r[i],NULL);
}
printf("\nEnd of program\n");
return 0;
}
void *reader(void *arg)
{
bool readable;
for(int i = 0; i < ITER_PER_THREAD; i++)
{
sem_wait(&mutex);
printf("Read current number: %d\n", num);
sem_post(&mutex);
}
sleep(1);
}
void *writer(void *arg)
{
for(int i=0; i<5; i++)
{
sem_wait(&mutex);
num = rand() % 10;
printf("Write random number: %d\n", num);
sem_post(&mutex);
}
sleep(1);
}
\ No newline at end of file
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment