본문 바로가기

TABA/OS

TABA Sep 20th - OS 실습 2

728x90
반응형

Lock Programming

- Shared Resource

- Critical Section 

 

 

멀티스레드 + 락 예제

 

#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
#include <assert.h>
#include <pthread.h>

int count = 0;
int nthread = 1;
int worker_loop_cnt = 1;

pthread_mutex_t lock;

static void *work(void* num) {
	int number = (int) num;
    
    pthread_mutex_lock(&lock); //lock
    
    for (int i = 0; i<worker_loop_cnt; i++)
    	count++;
    
    printf("Thread number %d : %d \n", number, count);
    
    pthread_mutex_unlock(&lock); //unlock
    
    return NULL;
}

int main(int argv, char *argv[]) {
	pthread_t *th;
    void *value;
    long i;
    
    if (argc<3) {
    	fprintf(stderr, "%sparameter : nthread, worker_loop_cnt \n", argv[0]);
        exit(-1);
    }
    
    nthread = atoi(argv[1]);
    worker_loop_cnt = atoi(argv[2]);
    
    th = malloc(sizeof(pthread_t) * nthread);
    
    pthread_mutex_init(&lock, NULL); // initialize the lock
    
    for (i=0; i<nthread; i++) {
    	assert(pthread_create(&th[i], NULL, work, (void*) i) == 0);
    }
    for (i=0; i<nthread; i++) {
    	assert(pthread_join(th[i], &value) == 0);
    }
    
    printf("Complete \n");
}

 


 

728x90
반응형

'TABA > OS' 카테고리의 다른 글

컨테이너를 사용하는 이유 (서버 가상화, 하이퍼바이저)  (0) 2022.11.08
TABA Sep 19th - OS 실습 1  (0) 2022.09.20