Last active
August 29, 2015 14:12
-
-
Save ochaochaocha3/5bab411a135bdbc1f02f to your computer and use it in GitHub Desktop.
pthread の例
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
CC=gcc | |
CFLAGS=-Wall | |
LIBS=-lpthread | |
TARGETS=pthread-test | |
pthread-test: pthread-test.c | |
$(CC) $(CFLAGS) -o $@ $< $(LIBS) | |
all: $(TARGETS) | |
clean: | |
rm -f *.o $(TARGETS) | |
.PHONY: all clean |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// マルチスレッドプログラムと mutex の使い方 | |
#include <stdio.h> | |
#include <sys/timeb.h> | |
#include <pthread.h> | |
#define N 50 | |
void* thread1(void* param); | |
void* thread2(void* param); | |
int count1 = 0; | |
int count2 = 0; | |
unsigned long time_to_print_count1; | |
unsigned long time_to_print_count2; | |
int terminating = 0; | |
pthread_mutex_t mutex; | |
int main(void) { | |
struct timeb now; | |
unsigned long now_msec; | |
pthread_t tid1, tid2; | |
puts("Enter を押すと終了します"); | |
pthread_mutex_init(&mutex, NULL); | |
ftime(&now); | |
now_msec = (unsigned long)now.time * 1000 + now.millitm; | |
time_to_print_count1 = now_msec + 1000; | |
time_to_print_count2 = time_to_print_count1 + 1000; | |
pthread_create(&tid1, NULL, thread1, NULL); | |
pthread_create(&tid2, NULL, thread2, NULL); | |
getchar(); | |
terminating = 1; | |
pthread_join(tid1, NULL); | |
pthread_join(tid2, NULL); | |
pthread_mutex_destroy(&mutex); | |
return 0; | |
} | |
void* thread1(void* param) { | |
struct timeb now; | |
unsigned long now_msec; | |
int i; | |
while (!terminating) { | |
ftime(&now); | |
now_msec = (unsigned long)now.time * 1000 + now.millitm; | |
if (now_msec >= time_to_print_count1) { | |
// mutex 間は他のスレッドから変数を変更できない | |
pthread_mutex_lock(&mutex); | |
printf("count1: "); | |
for (i = 0; i < N; ++i) { | |
printf("%2d ", count1++); | |
} | |
putchar('\n'); | |
pthread_mutex_unlock(&mutex); | |
time_to_print_count1 = now_msec + 2000; | |
} else if (now_msec >= time_to_print_count2) { | |
// mutex で変数を保護しないと他のスレッドから変数を変更できる | |
printf("count2: "); | |
for (i = 0; i < N; ++i) { | |
printf("%2d ", count2++); | |
} | |
putchar('\n'); | |
time_to_print_count2 = now_msec + 2000; | |
} | |
} | |
return NULL; | |
} | |
void* thread2(void* param) { | |
while (!terminating) { | |
// mutex で count1 を保護 | |
pthread_mutex_lock(&mutex); | |
count1 = 0; | |
pthread_mutex_unlock(&mutex); | |
// count2 は保護せずに変更する | |
count2 = 0; | |
} | |
return NULL; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment