2014-01-11 78 views
0

假設我想從用戶那裏接受輸入並在文本文件中爲該輸入執行搜索。搜索將針對每個字符用戶輸入執行。將會有一個循環執行搜索,並且會有另一個循環來檢查用戶是否輸入了新字符。如果用戶給出新的字符,第二個循環將重新啓動第一個循環。C++中的線程處理

請只解釋如何使用C++執行上述操作。我認爲線程需要被創建。

以下變量將被用於維護共同的價值觀:

static var` 
bool change; 


while(!change) 
{ 
change=false 
<<do something, like search in file>> 
} 

其他環路會像下面:

while(1) 
{ 
if(user enters another char) 
{ 
    var=new value input by the user; 
    change=true; 
} 
else change=false; 
} 

謝謝!

+2

使用'的std :: thread'和'的std :: atomic' – Brandon

+1

也許讀了一些[並行線程教程](https://computing.llnl.gov/tutorials/pthreads/)瞭解基本概念。另外,你的問題可能是特定於操作系統的(標準C++沒有辦法只讀取一個按鍵!)。也許你想使用[Qt](http://qt-project.org/) –

+0

http://thecodelesscode.com/case/126 =>爲什麼你確定線程是解決你的問題所必需的? –

回答

0

創建兩個主題:一個用於讀取用戶輸入,另一個用於執行搜索。

使用二進制信號,以便在消費者 - 生產者方式在兩個線程之間進行同步,即一個線程獲取信號量,另一個線程釋放它:

static BinarySemaphore binSem; 
static int inputCharacter = 0; 

static void ReadUserInput(); 
static void PerformSearch(); 

void Run() 
{ 
    BinarySemaphore_Init(&binSem,0); 
    CreateThread(ReadUserInput,LOWER_PRIORITY); 
    CreateThread(PerformSearch,HIGHER_PRIORITY); 
} 

static void ReadUserInput() 
{ 
    while (inputCharacter != '\n') 
    { 
     inputCharacter = getc(stdin); 
     BinarySemaphore_Set(&binSem); 
    } 
} 

static void PerformSearch() 
{ 
    while (inputCharacter != '\n') 
    { 
     BinarySemaphore_Get(&binSem,WAIT_FOREVER); 
     // <<do something, like search in file>> 
    } 
} 

請注意,您需要創建執行搜索的線程,優先級高於讀取用戶輸入的線程的優先級(如上面的代碼中所示)。

0

這樣的事情?現在我寫了這個關於ideone和他們的線程不適合我,所以我無法測試它,但是是..接近這個東西應該工作。可能是一個不好的例子。線程池將是最好的。

#include <iostream> 
#include <thread> 
#include <atomic> 
#include <queue> 
#include <mutex> 
#include <chrono> 

std::mutex lock; 
std::atomic<bool> stop(false); 
std::queue<std::function<void()>> jobs; 

void One() 
{ 
    while(!stop) 
    { 
     if (!jobs.empty()) 
     { 
      if (lock.try_lock()) 
      { 
       std::function<void()> job = jobs.front(); 
       jobs.pop(); 
       lock.unlock(); 

       job(); 
      } 
     } 
     std::this_thread::sleep_for(std::chrono::milliseconds(100)); 
    } 
} 

void Two() 
{ 
    std::string var; 

    while(true) 
    { 
     if (std::cin>> var) 
     { 
      std::lock_guard<std::mutex> glock(lock); 
      jobs.push([] {std::cout<<"Task added to the queue..\n";}); 
     } 
     else 
       break; 

     std::this_thread::sleep_for(std::chrono::milliseconds(100)); 
    } 
} 

int main() 
{ 
    std::thread T(One); 
    Two(); 

    stop = true; 
    T.join(); 
    return 0; 
}