マルチスレッド
pthreadでマルチスレッドのテスト。
これだと同時アクセスでcountが同じになる場合があるね。排他制御が必要みたい。
同時書き込みだから起こるけど、そこだけ注意すれば大丈夫かなw
これだと同時アクセスでcountが同じになる場合があるね。排他制御が必要みたい。
同時書き込みだから起こるけど、そこだけ注意すれば大丈夫かなw
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
int counter = 0;
void *thread1(void *args)
{
for (int i = 0; i < 3; i++) {
counter++;
printf("thread1: count %d\n", counter);
sleep(1);
}
}
int main()
{
pthread_t thread;
pthread_attr_t thread_attr;
pthread_attr_init(&thread_attr);
pthread_attr_setdetachstate(&thread_attr, PTHREAD_CREATE_DETACHED);
if(pthread_create(&thread, &thread_attr, thread1, NULL) != 0) {
perror("pthrad create error");
}
pthread_join(thread, NULL);
for (int i = 0; i < 3; i++) {
counter++;
printf("thread0: count %d\n", counter);
sleep(1);
}
pthread_exit(NULL);
}
結果
thread0: count 1 thread1: count 2 thread0: count 3 thread1: count 3 thread1: count 4 thread0: count 5