2012-10-14 18 views
0

我很難在線查找使用C++中的線程的信息。我需要的程序是在main()中創建兩個線程。這兩個線程從文本文件中指定的句子中獲取單詞,並根據每個單詞的起始字符打印出單詞。一個線程應該打印以元音開頭的單詞,另一個線程應該打印以輔音開頭的單詞。 main()不應該自己打印任何東西,並且這些單詞的順序應該與句子保持一致。這兩個線程需要互相屈服才能完成。不能使用同步技術。使用線程根據起始字符打印出單詞

我有文本文件被讀入一個向量,目前工作正常。我的代碼可以完成獲取正確的輸出,但不是以指定的方式。如果你能幫助我,我將不勝感激。謝謝。

#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(); 
} 
+0

產量應該是不必要的,一旦函數結束,線程就會產生 – jozefg

+0

他們似乎沒有必要,因爲他們看起來沒有什麼變化。如果我擺脫了下面的所有內容「ifs.close();」並改爲「線程一(cons,words [i]),two(vow,words [i]); one.join(); two.join();」那麼我相信它能正確打印所有東西。目前它以隨機的方式打印,我知道是線程的情況,但至少它不會留下任何東西。 – user1743959

+0

@mwigdahl:請閱讀作業標籤wiki。 – Mat

回答

1

我該知道的一個老話題,但這裏的答案是下面的函數使用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 

控制當開關應該發生基於標誌的布爾陣列和一個轉向變量,它們都位於全局共享內存空間中。沒有使用互斥量。