3スレッドを作成しています。 1を使用してユーザー1からの入力を読み取って文字列操作を行い、1を使用してコマンドプロンプトに書き込みます。3スレッド実行時のセグメンテーションフォルト
cout
文を設定して、どこでエラーが発生しているかを確認しました。私はスレッドを作成した後にいつかエラーが発生しているのがわかります。
スレッドが最初に実行されるものでなければならないと思います。 readerThread
関数を最初に実行し、次にconverterThread
を実行し、最後にwriterThread
を実行します。私はスレッドの実行順序を制限するためにこれらのロジックを実装する方法を探していました。データが到着する前に
pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
int counter = 0;
vector<string> readBuffer;
vector<string> writeBuffer;
int main(){
int readerInt,writerInt,converterInt;
pthread_t reader,writer,converter;
cout << "BEFORE"<<endl;
readerInt = pthread_create(&reader, NULL,readerThread,NULL);
converterInt = pthread_create(&converter,NULL,converterThread,NULL);
writerInt = pthread_create(&writer,NULL,writerThread,NULL);
cout << "AFTER" << endl;
pthread_join(reader,NULL);
pthread_join(converter,NULL);
pthread_join(writer,NULL);
return 0;
}
void * readerThread(void *unused){
while(1){
pthread_mutex_lock(&lock);
string readLine;
getline(cin,readLine);
counter++;
readBuffer.push_back(readLine);
pthread_mutex_unlock(&lock);
}
}
void * converterThread(void *unused){
while(1){
pthread_mutex_lock(&lock);
if(readBuffer.size() > 0){
replace(readBuffer[counter-1].begin(),readBuffer[counter-1].end(),' ','%');
writeBuffer.push_back(readBuffer[counter-1]);
}
pthread_mutex_unlock(&lock);
}
}
void * writerThread(void *unused){
while(1){
pthread_mutex_lock(&lock);
cout << writeBuffer[counter-1] << endl;
pthread_mutex_unlock(&lock);
}
}
[reader-writers](https://en.wikipedia.org/wiki/Readers-writers_problem)のような問題が発生します。あなたの最寄りのブラウザを参照してGoogleを起動すると、答えが待たれているはずです – smac89