我試圖偷看stdin,看看有沒有使用pthreads。我(認爲我)需要這樣做,因爲如果std中沒有任何內容,流訪問函數將阻止輸入。Peek stdin使用pthreads
我覺得做到這一點的方法是發射檢查標準輸入的pthread,然後sleep(1)並查看線程是否找到任何東西。
這是我到目前爲止。如果沒有任何東西被傳入程序,那麼它會按預期的方式睡眠,但如果某些東西在stdin中,則線程永遠不會被觸發。
#include <iostream>
#include <pthread.h>
#include <stdlib.h>
using namespace std;
void *checkStdIn(void *d){
char c = '\0';
c = cin.peek();
if (c){
cout << c << endl;
}
}
int main(int argc, char *argv[]){
pthread_t thread;
int rc;
rc = pthread_create(&thread, NULL, checkStdIn, NULL);
if (rc){
cerr << "Error no. " << rc << endl;
exit(EXIT_FAILURE);
}
sleep(2);
return 0;
}
程序結束後才能執行線程。 – 2011-07-27 17:01:26
爲什麼不睡覺()雖然補救? –
你的線程檢查一次輸入,找不到並終止。 –