c++ - 使用线程根据起始字符打印出单词

标签 c++ multithreading

我很难在网上找到有关在 C++ 中使用线程的信息。我需要我的程序做的是在 main() 中创建两个线程。这两个线程从文本文件中指定的句子中获取单词,并根据每个单词的起始字符打印出这些单词。一个线程应打印以元音开头的单词,另一个线程应打印以辅音开头的单词。 main() 本身不应打印任何内容,单词的顺序应与句子中的顺序保持一致。这两个线程需要相互屈服才能完成此操作。不能使用同步技术。

我将文本文件读入 vector ,目前工作正常。我的代码可以完成获得正确的输出,但不是以指定的方式。如果你能帮助我,我将不胜感激。谢谢。

#include <iostream>
#include <thread>
#include <fstream>
#include <string>
#include <iterator>
#include <vector>
#include <sstream>

using namespace std;

void cons(string temp){
    if (temp[0] != 'A' && temp[0] != 'a' && temp[0] != 'E'&& temp[0] != 'e'&& temp[0] != 'I'&& temp[0] != 'i'&& temp[0] != 'O'&& temp[0] != 'o'&& temp[0] != 'U'&& temp[0] != 'u') {
        cout << "cons:  " << temp << endl;
    }
    this_thread::yield();
}

void vow(string temp){
    if (temp[0] == 'A'|| temp[0] == 'a'|| temp[0] == 'E'|| temp[0] == 'e'|| temp[0] == 'I'|| temp[0] == 'i'|| temp[0] == 'O'|| temp[0] == 'o'|| temp[0] == 'U'|| temp[0] == 'u') { 
        cout << "vow:   " << temp << endl;
    }
    this_thread::yield();
}


int main(){
    string sentence, temp;
    ifstream ifs;
    ofstream ofs;
    vector <thread> wordThreads;

    ifs.open("phrase.txt");
    getline(ifs, sentence);
    istringstream s(sentence);
    istream_iterator<string> begin(s), end;
    vector<string> words(begin, end); 

    ifs.close();

    for (int i=0; i < 5; i++) {
        wordThreads.push_back(thread(cons, words[i]));
        wordThreads.push_back(thread(vow, words[i]));
    }

    for (thread& t: wordThreads) // loop with a range variable
    t.join(); 
}

最佳答案

我知道这是一个老话题,但这里的答案是在以下函数中使用 Petersons 算法:

loop
 flag[i] := true;   
 turn := j;    
 while flag[j] and turn = j do nothing;
 (critical section of code)  
 flag[i] := false;  
 (remainder section of code)   
end loop

它根据位于全局共享内存空间中的 Bool 标志数组和 turn 变量来控制何时应发生切换。没有使用互斥体。

关于c++ - 使用线程根据起始字符打印出单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12879236/

相关文章:

c++ - 将 3rd 方头文件放在源代码树中的什么位置?

c++ - DELAYLOAD 在 Qt LNK2001 : unresolved external symbol 中给出链接错误

c++ - 在 makefile 中描述头文件位置

c++ - C/C++ 编译器如何根据运算符的优先级和结合性来分离标记?

c++ - 将 C++11 线程操作与 QThread 操作混合

数据库或用户级锁

java - 在java中使用多线程并行化for循环

python - 与 celery 中的任务实例相关的属性

java - 在 Java 中将 Iterator 传递给线程

c++ - getaddrinfo() 只返回::1 作为 IPV6 地址,