所以我创建了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);
}
}
听起来像[读者 - 作者](https://en.wikipedia.org/wiki/Readers-writers_problem)问题。请咨询您最近的浏览器并引导谷歌,答案应该等待 – smac89