Recent Posts
printf("ho_tari\n");
Chapter 18 (thread, mutex) 본문
<thread4.c>
#include <stdio.h>
#include <pthread.h>
#define NUM_THREAD 100
void * thread_inc(void * arg);
void * thread_des(void * arg);
long long num=0;
pthread_mutex_t mutex;
int main(int argc, char *argv[])
{
pthread_t thread_id[NUM_THREAD];
int i;
pthread_mutex_init(&mutex, NULL);
printf("sizeof long long: %d \n", sizeof(long long));
for(i=0; i<NUM_THREAD; i++)
{
if(i%2)
pthread_create(&(thread_id[i]), NULL, thread_inc, NULL);
else
pthread_create(&(thread_id[i]), NULL, thread_des, NULL);
}
for(i=0; i<NUM_THREAD; i++)
pthread_join(thread_id[i], NULL);
printf("result: %lld \n", num);
pthread_mutex_destroy(&mutex);
return 0;
}
void * thread_inc(void * arg)
{
int i;
pthread_mutex_lock(&mutex);
for(i=0; i<50000000; i++){
num+=1;
}
pthread_mutex_unlock(&mutex);
return NULL;
}
void * thread_des(void * arg)
{
int i;
pthread_mutex_lock(&mutex);
for(i=0; i<50000000; i++){
num-=1;
}
pthread_mutex_unlock(&mutex);
return NULL;
}
<compile 결과>
'TCP IP 소켓 프로그래밍' 카테고리의 다른 글
Chapter 18 (semaphore, thread) (0) | 2023.10.11 |
---|---|
Chapter 18 (semaphore) (0) | 2023.10.11 |
Chapter 9 (get, set) (0) | 2023.10.11 |
Chapter 8 (gethostbyname, gethostbyaddr) (0) | 2023.10.11 |
Chapter 5 (echo_client2) (0) | 2023.10.11 |