2017-09-23 102 views
0

我在寫一個創建兩個線程的程序。每個線程負責讀取一個文本文件,每行一個字符。Pthread同步:兩個文本文件的前後讀取

h 
0 
h 
0 
... 

第二的格式如下::

第一像被格式化

0 
i 
0 
i 
0 
i 

有時可以有後彼此多個字母,或彼此先後多個零。但是,一個確定的是,如果一個文件的一行上有一個字母,第二個文件的相應行將有一個0,反之亦然。

線程應該保持讀取文件輸入到全局字符數組中,直到它們達到零。此時,他們允許另一個線程接管。他們會一直往前走,直到兩個文件都被完全讀取。 (1)很多h的變化,其次是許多i或(2)(正確答案)hihihi的連續流,或(3)有時很多我的其次是許多h。所以,我知道我的同步方法已關閉。

這是我的線程中的一個的示例: (注意兩個線程是完全一樣的,除了被打開的文件。)

void *getMessage1() 
{ 
FILE *studentOne = fopen("Student1", "r"); 

size_t howManyChars; 
char *placeHolderChars; 
int count = 1; 
while (count < 501) 
{ 
    placeHolderChars = NULL; 
    getline(&placeHolderChars, &howManyChars, studentOne); 

    if(strcmp(placeHolderChars, "0\n") == 0) //if we've reached a zero 
    { 

     pthread_mutex_unlock(&lock); 
    } 
    else 
    { while(1) 
     { 
      if(pthread_mutex_trylock(&lock) == 0) 
      { 

       break; 
      } 
     } 

     if(strlen(placeHolderChars)>0) 
     { 
      placeHolderChars[1] = '\0'; 
     } 

     strcat(message,placeHolderChars); 
    } 

    free(placeHolderChars); 

    if(feof(studentOne)) 
    { 

     pthread_mutex_unlock(&lock); //unlock 
     fclose(studentOne); 
     break; 
    } 
    count++; 

} 

return 0; 
} 

這是我的主要方法:

int main(void) 
{ 
pthread_t id1; 
pthread_t id2; 

pthread_create((&id1), NULL, getMessage1, NULL); 
pthread_create((&id2), NULL, getMessage2, NULL); 

pthread_join(id1, NULL); 
pthread_join(id2, NULL); 

int j; 

for (j = 0; j < 1001; j++) 
{ 
    printf ("%c ",message[j]); 
} 

return 0; 
} 

如果我能更好地使用鎖定,解鎖,等待和/或信號創建具有一致結果的工作同步技術,我將不勝感激。

+0

信號量。你不能用互斥鎖來做到這一點。多重複數據刪除。 –

+0

我的教授實際上建議我們使用互斥體,因爲他聲稱它會使它容易得多。所以,我應該廢除互斥體並使用二進制信號量或什麼? – Selena

+0

此外,我應該考慮只有一個函數,這兩個線程使用? (然後他們通過文件作爲參數?)會有什麼區別? – Selena

回答

1

下面是一個你想要的程序的嘗試。雖然沒有充分測試);

#include <iostream> 
#include <fstream> 
#include <string> 

#include <cassert> 
#include <pthread.h> 



using std::cout; 
using std::ifstream; 
using std::string; 

const string FILE1("file1.txt"); 
const string FILE2("file2.txt"); 

enum State 
{ 
    UNINITIALIZED, 
    THREAD_ONE_READS, 
    THREAD_TWO_READS 
}; 

struct ThreadInfo 
{ 
    State state; 
    string filename; 
}; 

State state = UNINITIALIZED; 
pthread_mutex_t mut = PTHREAD_MUTEX_INITIALIZER; 
pthread_cond_t cond = PTHREAD_COND_INITIALIZER; 

void* thread_func(void* arg) 
{ 
    // Open file 'h'.                                                                                                     

    ThreadInfo ti = *reinterpret_cast<ThreadInfo*>(arg); 
    ifstream infile; 
    infile.open (ti.filename.c_str(), std::ifstream::in); 

    // while (not EOF)                                                                                                     
    // Read 'h' or 'i': until 0 reached. Wake up other thread.                                                                                          

    string line; 
    getline(infile, line); 
    while (infile.good()) 
    { 
     cout << "Thread " << pthread_self() << " read " << line << '\n'; 
     pthread_mutex_lock(&mut); 
     while (state == ti.state) 
     { 
      pthread_cond_wait(&cond, &mut); 
     } 
     pthread_mutex_unlock(&mut); 

     assert(line.length() == 1); 
     if (line[0] == '0') 
     { 
      pthread_mutex_lock(&mut); 
      state = ti.state; 
      cout << "Got 0, transferring, setting state to " << state << '\n'; 
      pthread_cond_signal(&cond); 
      pthread_mutex_unlock(&mut); 
     } 
     else 
     { 
      cout << "Read char: " << line << '\n'; 
     } 
     getline(infile, line); 
    } 

    pthread_mutex_lock(&mut); 
    state = ti.state; 
    cout << "Finishing thread, transferring, setting state to " << state << '\n'; 
    pthread_cond_signal(&cond); 
    pthread_mutex_unlock(&mut); 
} 

int main() 
{ 
    // Create thread 1                                                                                                     
    // Create thread 2                                                                                                     

    pthread_t thread_one_handle; 
    pthread_t thread_two_handle; 
    state = THREAD_ONE_READS; 
    int result; 

    ThreadInfo info1 = { THREAD_TWO_READS, FILE1 }; 
    result = pthread_create(&thread_one_handle, NULL, thread_func, &info1); 
    assert(result == 0); 

    ThreadInfo info2 = { THREAD_ONE_READS, FILE2 }; 
    result = pthread_create(&thread_two_handle, NULL, thread_func, &info2); 
    assert(result == 0); 

    result = pthread_join(thread_one_handle, NULL); 
    assert(result == 0); 
    result = pthread_join(thread_two_handle, NULL); 
    assert(result == 0); 
    cout << "main(): joined both worker threads, ending program.\n"; 

    return 0; 
} 
+0

@Selena對此有幫助嗎?我看到你兩次發佈了相同的問題,並接受了另一個相同問題的答案;( –

+0

我發現這個問題總是用C標記,而不是C++,但是這個答案是用C++編寫的,這可能限制了它的用處OP。我還注意到同一主題的另一個問題(在頂部的評論中) –

+0

@JonathanLeffler:由於在我的回答中使用C++特有的功能非常有限,因此轉換爲old-skool C應該是微不足道的。 –