Posix线程用c ++编写

时间:2009-02-24 03:32:04

标签: c++ multithreading posix

如何在linux c ++中实现posix线程。当保存为“.c并使用c编译器运行时,smme程序是可以的。但在c ++中它给出错误..

我认为编译时我犯了错误 是否有任何标签要包括像“-lpthread”的c ++

有人可以发送有效的代码......?

其实这是我的代码

int cooperbussman :: startlistenthread()
{
        if(pthread_create(&m_thread,0,&packetreadertask,0)<0)
        {
                cout<<"Unable to create the thread Startlistenthread\n";
                return -1;
        }
        return 1;

我得到的错误是

cooperbussman.cpp: In member function âint cooperbussman::startlistenthread()â:
cooperbussman.cpp:76: error: invalid conversion from âvoid* (*)()â to âvoid* (*)(void*)â
cooperbussman.cpp:76: error:   initializing argument 3 of âint pthread_create(pthread_t*, const pthread_attr_t*, void* (*)(void*), void*)â

3 个答案:

答案 0 :(得分:5)

您的packetreadertask函数必须是一个以void *为参数的函数。这是重要的错误消息:

cooperbussman.cpp:76: error: invalid conversion from âvoid* (*)()â to âvoid* (*)(void*)â

你的函数声明如下:

void *packetreadertask();

必须是:

void *packetreadertask(void *);

答案 1 :(得分:4)

您可以考虑使用Boost.Threads。它在C ++中为您提供了一些简单的语义,而不是支持它的平台上的pthread。

但....没有理由不能在C ++程序中使用pthreads。您的错误可能是由于符号错位造成的,但是如果没有看到您的代码或至少是您的编译器输出,我们就无法更准确地帮助您。

答案 2 :(得分:2)

使用g ++时使用-lpthreads就像使用gcc一样。只要您不尝试使用非静态成员函数指针作为线程,那么pthreads应该可以正常使用C ++。