2014-03-03 48 views
0

我正嘗試使用pthread從命令行讀取輸入。 pthread會調用一個閱讀功能。遇到一些麻煩,我已經閱讀了POSIX文檔。感謝幫助!使用pthreads讀取輸入

int main(int argc , char *argv[]) 
{ 
    pthread_t client_thread; // client thread 
    int rc; 
    string msg; 
    cout<<"Please enter a message to send to the server: "<<endl; 
    pthread_create(&client_thread, NULL, readerT, &msg); 

    cout<<"Msg is: "<<msg<<endl; 

    return 0; 
} 

void * readerT(string * temp) 
{ 
    cout<<"GOT IN HERE:\n"<<endl; 
    getline(cin,*temp); 
} 

當前錯誤消息:

Client.cpp: In function ‘int main(int, char**)’: 
Client.cpp:33: error: invalid conversion from ‘void* (*)(std::string*)’ to ‘void* (*)(void*)’ 
Client.cpp:33: error: initializing argument 3 of ‘int pthread_create(pthread_t*, const pthread_attr_t*, void* (*)(void*), void*)’ 
+1

加入創建的線程,以便主線程不會結束。 – Whoami

+0

我加了pthread_join(client_thread,NULL);在cout <<「之後msg是...但是我得到了一堆關於無效轉換的錯誤:( – Masterminder

+0

1)檢查線程創建的返回值,確保你編輯了具有適當錯誤信息的問題,以便工程師可以 – Whoami

回答

1
#include<iostream> 
#include <pthread.h> 
using namespace std; 

void * readerT(void*); 
int main(int argc , char *argv[]) 
{ 
    pthread_t client_thread; // client thread 
    int rc; 
    string msg; 
    cout<<"Please enter a message to send to the server: "<<endl; 
    pthread_create(&client_thread, NULL, readerT, &msg); 
    pthread_join(client_thread,NULL); 
    cout<<"Msg is: "<<msg<<endl; 

    return 0; 
} 

void * readerT(void * temp) 
{ 
    string *tmp = (string*)(temp); 
    getline(cin,*tmp); 
} 

希望,將工作...(試着分析什麼是錯與您的代碼:-))

+0

雖然你大致指向一個錯誤,但它仍然與問題無關。回答應該解釋什麼是錯的,以及如何修復(如果有的話) – alk

+0

我想你還沒有看到原始問題......錯誤是顯而易見的,是的,我沒有使用pthread,所以沒有意識到語法.. – HadeS

+0

我想你應該訪問這個之前說那..... ..... http://www.cplusplus.com/reference/string/string/getline/ – HadeS

2

剛剛看過的錯誤消息:

Client.cpp:33: error: invalid conversion from ‘void* (*)(std::string*)’ to ‘void* (*)(void*)’ 

線程函數必須是o F型:

void * (*)(void *) 

要改變這種

void * readerT(string * temp) 

void * readerT(void * temp) 
0

我覺得有可能是你的代碼的兩個問題

  • 線程CALLBACK_FUNCTION是錯誤

    void *readerT(string *temp)

    void *readerT(void *temp)

  • 使用加入功能在主線程

如果你不這樣做,主線程會很快創建read_in後退出線程,所以使用連接函數等待線程完成。