2014-03-03 101 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后退出线程,所以使用连接函数等待线程完成。