Arduinoだとタイマー割り込みを使って処理したいところですが残念ながら私の調べた限りRaspberry Piでは無さそうなのでC言語とスレッドを利用し近い処理をさせることにしました。
$ vi thread_test.c
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>
void *thread_function1( void *ptr );
void *thread_function2( void *ptr );
int main(void){
pthread_t thread1, thread2;
useconds_t tick1 = 200000;
useconds_t tick2 = 2000000;
pthread_create( &thread1, NULL, thread_function1, (void *) &tick1);
pthread_create( &thread2, NULL, thread_function2, (void *) &tick2);
pthread_join( thread1, NULL);
pthread_join( thread2, NULL);
return 0;
}
void *thread_function1(void *ptr){
useconds_t tick = *( int * )ptr;
while(1){
printf("function1\n");
usleep(tick);
}
}
void *thread_function2(void *ptr){
useconds_t tick = *( int * )ptr;
while(1){
printf("function2\n");
usleep(tick);
}
}
コンパイルします
$ gcc thread_test.c -pthread
実行
$ ./a.out
しかし、これでは共有資源を利用したプログラムを書いた場合取り合いになり下手をするとデータが失われたりする場合があるため排他制御するようにします。
$ vi thread_test.c
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>
void *thread_function1( void *ptr );
void *thread_function2( void *ptr );
pthread_mutex_t mutex;
pthread_cond_t cond;
int count = 0;
useconds_t tick1 = 200000;
useconds_t tick2 = 2000000;
int main(void){
pthread_t thread1, thread2;
pthread_mutex_init(&mutex, NULL);
pthread_create( &thread1, NULL, thread_function1, (void *) &tick1);
pthread_create( &thread2, NULL, thread_function2, (void *) &tick2);
pthread_join( thread1, NULL);
pthread_join( thread2, NULL);
pthread_mutex_destroy(&mutex);
return 0;
}
void *thread_function1(void *ptr){
useconds_t tick = *( int * )ptr;
while(1){
pthread_mutex_lock(&mutex);
printf("function1 %d\n",count++);
pthread_mutex_unlock(&mutex);
usleep(tick);
}
}
void *thread_function2(void *ptr){
useconds_t tick = *( int * )ptr;
while(1){
pthread_mutex_lock(&mutex);
printf("function2 %d\n",count++);
pthread_mutex_unlock(&mutex);
usleep(tick);
}
}
コンパイルします
$ gcc thread_test.c -pthread
実行
$ ./a.out
function2 0
function1 1
function1 2
function1 3
function1 4
function1 5
function1 6
function1 7
function1 8
function1 9
function1 10
function2 11
function1 12
function1 13
function1 14
function1 15
function1 16
function1 17
function1 18
0 Comments.