【发布时间】:2016-11-07 22:31:13
【问题描述】:
所以我正在创建 3 个线程。 1 读取用户的输入 1 执行一些字符串操作, 1 写入命令提示符。
我已经设置了一些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);
}
}
【问题讨论】:
-
听起来像是readers-writers 的问题。咨询您最近的浏览器并启动谷歌,答案应该正在等待
标签: c++ linux multithreading segmentation-fault