PR
Category
Keyword Search
Comments
Freepage List
前回のプログラムだが、よく考えるとフルmutex,エンプティmutexは獲得できれば、データを書くスペースがある、読み出すべきデータがある、ことをそれぞれ意味するようです。
ここでfifoの長さを1とすれば、データの読み書きをする場所は1箇所になり、データバッファへのインデックス変数ももはや不要になります。2つのmutex+データバッファを単位として、この配列をつくった方がスマートな実装になりそうです。(fifo2.c)
ついでに言えば、2つのmutex+データバッファの「オブジェクト」とにしたほうが見通しがよくなりそう・・・ c++は古い仕様しかわからない(orz)ので、今回はこれでよしにします…
(2009/4/4追記)
下のプログラムはいわゆる「スレッド・セーフ」ではないライブラリ関数が使われています。(printfなど)よって、正しく動作しない可能性があります。(実際には試した範囲では問題は起きていませんが) 恥さらしですが、サンプルのプログラムはそのまま、晒しておきます。
----- fifo2.c ------ // gcc file_name.c -lpthread
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
// FIFO control
#define FIFOSIZE (100)
typedef struct {
int buf ;
pthread_mutex_t wLock, rLock ;
} _BufType ;
static _BufType fifo[FIFOSIZE] ;
void * thread1( void* pParam) {
int i, index ;
for( i = 0, index=0 ; i < 1000 ; i++ ) {
pthread_mutex_lock( &(fifo[index].wLock ) ) ;
// start of writing data to buffer
fifo[index].buf = i ;
// end of writing data to buffer
pthread_mutex_unlock( &(fifo[index].rLock ) ) ;
if( (++index) >= FIFOSIZE ) {
index = 0 ;
}
printf("push %d %d\n", index, i ) ;
usleep( (rand() % 100)) ;
}
}
void * thread2( void* pParam) {
int i, index, d ;
for( i = 0, index=0 ; i < 1000 ; i++ ) {
pthread_mutex_lock( &(fifo[index].rLock ) ) ;
// start of reading data from buffer
d = fifo[index].buf ;
// end of reading data to buffer
pthread_mutex_unlock( &(fifo[index].wLock ) ) ;
if( (++index) >= FIFOSIZE ) {
index = 0 ;
}
printf("pop_ %d %d\n", index, d ) ;
usleep( (rand() % 100) +10) ;
}
}
int main(void) {
int i ;
pthread_t tid1, tid2;
// initialize mutex of FIFOs
for( i = 0 ; i < FIFOSIZE ; i++ ) {
// fifo[i].wLock = PTHREAD_MUTEX_INITIALIZER
// fifo[i].wLock = _Lock
pthread_mutex_init( &(fifo[i].wLock), NULL) ;
pthread_mutex_unlock( &(fifo[i].wLock )) ;
//fifo[i].rLock = pthread_mutexattr_init( NULL )
pthread_mutex_init( &(fifo[i].rLock), NULL) ;
pthread_mutex_lock( &(fifo[i].rLock )) ;
}
pthread_create(&tid1, NULL, thread1, NULL);
pthread_create(&tid2, NULL, thread2, NULL);
pthread_join(tid1,NULL) ;
pthread_join(tid2,NULL) ;
return 0 ;
}
PureDataはじめました… 2009.11.14
UbuntuにVMplayer 2009.04.19
bash の()のPIDは?Bashではまるシリー… 2009.04.17 コメント(2)